PNS PNS - 2 years ago 148
Java Question

Java date parsing with microsecond or nanosecond accuracy

According to the SimpleDateFormat class documentation,

Java
does not support time granularity above milliseconds in its date patterns.

So, a date string like


  • 2015-05-09 00:10:23.999750900 // The last 9 digits denote nanoseconds



when parsed via the pattern


  • yyyy-MM-dd HH:mm:ss.SSSSSSSSS // 9 'S' symbols



actually interprets the whole number after the
.
symbol as (nearly 1 billion!) milliseconds and not as nanoseconds, resulting in the date


  • 2015-05-20 21:52:53 UTC



i.e. over 11 days ahead. Surprisingly, using a smaller number of
S
symbols still results in all 9 digits being parsed (instead of, say, the leftmost 3 for
.SSS
).

There are 2 ways to handle this issue correctly:


  • Use string preprocessing

  • Use a custom SimpleDateFormat implementation



Would there be any other way for getting a correct solution by just supplying a pattern to the standard
SimpleDateFormat
implementation, without any other code modifications or string manipulation?

Answer Source

Nope

No, you cannot use SimpleDateFormat to handle nanoseconds.

But your premise that…

Java does not support time granularity above milliseconds in its date patterns

…is no longer true as of Java 8.

java.time

SimpleDateFormat, and the related java.util.Date/.Calendar classes are now outmoded by the new java.time package found in Java 8 (Tutorial).

The new java.time classes support nanosecond resolution. That support includes parsing and generating nine digits of fractional second. For example, when you use the java.time.format DateTimeFormatter API, the S pattern letter denotes a "fraction of the second" rather than "milliseconds", and it can cope with nanosecond values.

    2013-08-20T12:34:56.123456789Z

java.sql.Timestamp

The java.sql.Timestamp class also handles nanosecond resolution, but in an awkward way. Generally best to do your work inside java.time classes.

Until JDBC drivers are updated to directly support java.time data types, you can use toInstant and from methods to go back and forth between java.sql.Timestamp and java.time.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download