SimpleDateFormat parsing results are odd

I want to parse dates from a filesystem and get them in this format:

2013-07-29 14:49:53.813588954 +0200

Therefore my pattern looks like this

yyyy-MM-dd HH:mm:ss.SSSSSSSSS Z

And finally my code:

String rawDate = "2013-07-29 14:49:53.813588954 +0200";

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSSSSS Z");
Date date = sdf.parse(rawDate);

SimpleDateFormat out = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String parsedDate = out.format(date);

System.out.println(rawDate + " -> " + parsedDate);

But my output looks like this:

2013-07-29 14:49:53.813588954 +0200 -> 2013-08-08 00:49:41.000000954 +0200

I even tried with setLenient(false) but then I got a ParseException.

Jon Skeet
people
quotationmark

You've parsed 813588954 as a number of milliseconds - that's over 9 days, and it's being added to 2013-07-29 14:49:53.

Basically, SimpleDateFormat doesn't handle parsing nanoseconds, and java.util.Date only supports millisecond precision anyway.

If you can possibly use Java 8, I'd recommend using java.time for everything - don't use java.util.Date at all. If you can use java.time for parsing but have to use java.util.Date for the rest, that will at least help.

If you can't use Java 8 at all, I'd suggest manually modifying the string to truncate the nanoseconds to milliseconds and then parse with SimpleDateFormat using a pattern that uses .SSS.

people

See more on this question at Stackoverflow