Reputation: 909
Why doesn't the following work? It appears that the literal zero at the end is the cause...
final DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS0");
format.setLenient(false);
String d = format.format(new Date());
System.out.println(format.parse(d));
Upvotes: 4
Views: 25138
Reputation: 85779
I do not know why would you need to add the zero (0) at the end of your pattern, but you should wrap the not pattern letters inside '' to make them work:
final DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS'0'");
More info:
SimpleDateFormat
, Examples section at the beginning of the documentation.The problem with your code is in this line
System.out.println(format.parse(d));
Trying to parse more than 3-digit milliseconds to java.util.Date will result in an exception. The pattern to parse the String should be
"yyyy-MM-dd HH:mm:ss.SSS" //without the zero at the end, now your whole code will work...
If you're working with nanoseconds or your data have them, you could ignore these values, also nanoseconds are not supported in Java Date/Time API (in the documentation they don't even mention it).
If you really, really need to have the nanoseconds for diverse purposes, then you should stick to use a String instead of a Date object.
Upvotes: 7