Wrong output of SimpleDateFormat with milliseconds ( SSSSSSS )

I am parsing MS SQL date with java.text.SimpleDateFormat but it is giving me wrong output. According to the documentation of SimpleDateFormat, it should parse correctly or may be I am missing something.

System.out.println( new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss.SSSSSSS" ).parse( "2016-02-29 13:02:50.2870000 +00:00" ) );
Incorrect Output with milliseconds format
>> Mon Feb 29 13:50:40 PKT 2016

However if I try without SSSSS it gives me expected result.

System.out.println( new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ).parse( "2016-02-29 13:02:50.2870000 +00:00" ) );
Correct Output without milliseconds format
>> Mon Feb 29 13:02:50 PKT 2016

Why there is difference of 47 minutes and 50 seconds ?

Jon Skeet
people
quotationmark

You've specified that there are 2870000 milliseconds - which is 47 minutes and 50 seconds.

It's important to note that in SimpleDateFormat, S is a milliseconds specifier, not a "fraction of second" specifier. Basically, if you're specifying more than SSS, it's going to go badly.

Now in terms of your issue - if you're getting a date from a database, you shouldn't have a string value to parse at all - you should have a java.sql.Date or java.sql.Timestamp. If you're storing date/time data as text, that's a problem you should address separately.

If you have to do this parsing, I'd just chop off the last four digits and parse it with .SSS at the end instead. It's not like a java.util.Date can maintain sub-millisecond precision anyway.

Alternatively, you could use java.time or Joda Time as much better date/time APIs - and java.time supports nanosecond precision. Within DateTimeFormatter, the S format specifier does mean "fraction-of-second".

people

See more on this question at Stackoverflow