Why Does the New Java 8 Date Time API Not Have Nanosecond Precision

Why does the new Java 8 Date Time API not have nanosecond precision?

The java.time API in general does have nanosecond precision. For example:

DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd'T'HH:mm:ss,nnnnnnnnnZ");
OffsetDateTime odt = OffsetDateTime.of(2015, 11, 2, 12, 38, 0, 123456789, ZoneOffset.UTC);
System.out.println(odt.format(formatter));

Output:

2015-11-02T12:38:00,123456789+0000

However, it's the clock value returned by OffsetDateTime.now() which is returning a value which only has milliseconds.

From Clock implementation in Java 8:

The clock implementation provided here is based on System.currentTimeMillis(). That method provides little to no guarantee about the accuracy of the clock. Applications requiring a more accurate clock must implement this abstract class themselves using a different external clock, such as an NTP server.

So there's nothing inherently imprecise here - just the default implementation of Clock using System.currentTimeMillis(). You could potentially create your own more precise subclass. However, you should note that adding more precision without adding more accuracy probably isn't terribly useful. (There are times when it might be, admittedly...)

Java 8 LocalDateTime.now() only giving precision of milliseconds

tl;dr

Is it possible to get microseconds in Java 8?

No, not in Java 8. Use Java 9 or later.

Instant.now()  // Returns a value in microseconds in Java 9 and later, but is restricted to mere milliseconds in Java 8.

This refers to implementations of Java based on the OpenJDK open-source code. Others may vary.

Java 9 and later

The implementations of Java 9 based on OpenJDK have a fresh implementation of java.time.Clock capable of capturing the current moment in resolution finer than milliseconds (three digits of decimal fraction).

The actual resolution depends on the limits of your host computer hardware clock. On macOS Sierra with Oracle Java 9.0.4, I am getting current moment with microseconds (six digits of decimal fraction).

Instant.now().toString()

2018-03-09T21:03:33.831515Z

Java 8

The java.time classes were new in Java 8. These classes are defined to carry nanoseconds (nine digits of decimal fraction). But capturing the current moment was limited to only milliseconds in Java 8, and enhanced in Java 9 to capture the current moment in finer microseconds.

2018-03-09T21:03:33.831Z

Other issues

System.currentTimeMillis()

If I get System.currentTimeMillis() and System.nanoTime()

No need to use System.currentTimeMillis() ever again. Instead use java.time.Instant for a moment in UTC with a resolution as fine as nanoseconds.

If you really need a count of milliseconds from the epoch reference of 1970-01-01T00:00Z, ask the Instant object. Be aware of data loss, as you would be ignoring any microseconds or nanoseconds present in the Instant.

long millisSinceEpoch = instant.now().toEpochMilli() ;

Is there a way that I can parse clock time from these values?

Yes, you can convert a count of milliseconds since epoch of 1970-01-01T00:00Z to a Instant.

Instant instant = Instant.ofEpochMilli( millisSinceEpoch ) ;

System.nanoTime()

As for System.nanoTime(), that is intended for tracking elapsed time, such as benchmarking your code’ performance. Calling System.nanoTime() does not tell you anything about the current date-time.

This value is a count of nanoseconds since some undocumented origin point in time. In practice, I have seen the number appear to track time since the JVM launched, but this behavior is not documented and so you should not rely upon it.

LocalDateTime is not a moment

My problem is that I need to do logging using both Java and Javascript and they need to have a consistent microsecond field across both of them.

Firstly, for logging you should not be using LocalDateTime class. That class purposely lacks any concept of time zone or offset-from-UTC. As such, a LocalDateTime does not represent a moment, is not a point on the timeline. A LocalDateTime is an idea about potential moments along a range of about 26-27 hours. Use LocalDateTime only if the zone/offset is unknown (not a good situation), or if this represents something like "Christmas Day starts on first moment of Decemeber 25, 2018", where Christmas starts at different moments for different regions around the globe, starting first in the far East (Pacific), and moving westward midnight after successive midnight.

For logging you should be using UTC. In Java, that would be the Instant class, always in UTC by definition. Just call Instant.now().

When serializing to text such as for logging, always use the standard ISO 8601 formats. The java.time classes use these standard formats by default when parsing/generating strings. You saw examples above in this Answer.

See another Question, What's the difference between Instant and LocalDateTime?.

Table of date-time types in Java, both modern and legacy

ISO 8601

In ISO 8601, the decimal fraction of a second can have any number of digits. So you really should not care about whether the logged event was recorded in milliseconds, microseconds, or nanoseconds.

Instant instant = Instant.parse( "2018-03-09T21:03:33.123456789Z" ) ;
Instant instant = Instant.parse( "2018-03-09T21:03:33.123456Z" ) ;
Instant instant = Instant.parse( "2018-03-09T21:03:33.123Z" ) ;

Truncate

If you really believe you need uniform resolution, you can truncate a Instant.

Instant instant = Instant.now().truncatedTo( ChronoUnit.MILLIS ) ; // Strip away any microseconds or nanoseconds.

Don't worry about resolution

My problem is that I need to do logging using both Java and Javascript and they need to have a consistent microsecond field across both of them.

Firstly, I doubt you really need to care about this. If you use standard ISO 8601 format, and the Instant class in Java, you can serialize and re-hydrate a moment successfully in millis, micros, or nanos.

And the ISO 8601 formatted strings will conveniently alphabetize chronologically even if the fractional second resolution varies.

Secondly, if you are trying to track actual moments to microseconds for some reason, you are likely to be disappointed. As of 2018, conventional computer clocks are not reliable in the microsecond range.



About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
    • Java 9 brought some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android (26+) bundle implementations of the java.time classes.
    • For earlier Android (<26), the process of API desugaring brings a subset of the java.time functionality not originally built into Android.
      • If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….

LocalDateTime.now() has different levels of precision on Windows and Mac machine

The precision is different because LocalDateTime.now() uses a system default Clock.

Obtains the current date-time from the system clock in the default time-zone.

This will query the system clock in the default time-zone to obtain the current date-time.

...

The link in this Javadoc takes you to Clock.systemDefaultZone() which states (emphasis mine):

Obtains a clock that returns the current instant using the best available system clock, converting to date and time using the default time-zone.

This clock is based on the best available system clock. This may use System.currentTimeMillis(), or a higher resolution clock if one is available.

...

Which clock Java uses can depend on a lot of things and it looks like your Mac computer has a clock with microsecond precision whereas your Windows computer has a clock with millisecond precision. I'm not aware of any way to increase the precision of a clock but you can definitely decrease the precision so that it matches across platforms.

One option is to do as Ole V.V. does in his answer and use LocalDateTime.truncatedTo(TemporalUnit).

Another option is to plug in your own Clock and use LocalDateTime.now(Clock). If possible, I would use Clock.tickMillis(ZoneId) since this method returns a Clock that truncates to milliseconds.

Obtains a clock that returns the current instant ticking in whole milliseconds using the best available system clock.

This clock will always have the nano-of-second field truncated to milliseconds. This ensures that the visible time ticks in whole milliseconds. The underlying clock is the best available system clock, equivalent to using system(ZoneId).

...

Since:
9

Current time in microseconds in java

No, Java doesn't have that ability.

It does have System.nanoTime(), but that just gives an offset from some previously known time. So whilst you can't take the absolute number from this, you can use it to measure nanosecond (or higher) precision.

Note that the JavaDoc says that whilst this provides nanosecond precision, that doesn't mean nanosecond accuracy. So take some suitably large modulus of the return value.

Java date parsing with microsecond or nanosecond accuracy

tl;dr

LocalDateTime.parse(                 // With resolution of nanoseconds, represent the idea of a date and time somewhere, unspecified. Does *not* represent a moment, is *not* a point on the timeline. To determine an actual moment, place this date+time into context of a time zone (apply a `ZoneId` to get a `ZonedDateTime`). 
"2015-05-09 00:10:23.999750900" // A `String` nearly in standard ISO 8601 format.
.replace( " " , "T" ) // Replace SPACE in middle with `T` to comply with ISO 8601 standard format.
) // Returns a `LocalDateTime` object.

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, 9, 10 and later with java.time classes built-in. And not really true of Java 6 and Java 7 either, as most of the java.time functionality is back-ported.

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.

Instant

As an example, the Instant class represents a moment in UTC. Its toString method generates a String object using the standard ISO 8601 format. The Z on the end means UTC, pronounced “Zulu”.

instant.toString()  // Generate a `String` representing this moment, using standard ISO 8601 format.

2013-08-20T12:34:56.123456789Z

Note that capturing the current moment in Java 8 is limited to millisecond resolution. The java.time classes can hold a value in nanoseconds, but can only determine the current time with milliseconds. This limitation is due to the implementation of Clock. In Java 9 and later, a new Clock implementation can grab the current moment in finer resolution, depending on the limits of your host hardware and operating system, usually microseconds in my experience.

Instant instant = Instant.now() ;  // Capture the current moment. May be in milliseconds or microseconds rather than the maximum resolution of nanoseconds.

LocalDateTime

Your example input string of 2015-05-09 00:10:23.999750900 lacks an indicator of time zone or offset-from-UTC. That means it does not represent a moment, is not a point on the timeline. Instead, it represents potential moments along a range of about 26-27 hours, the range of time zones around the globe.

Pares such an input as a LocalDateTime object. First, replace the SPACE in the middle with a T to comply with ISO 8601 format, used by default when parsing/generating strings. So no need to specify a formatting pattern.

LocalDateTime ldt = 
LocalDateTime.parse(
"2015-05-09 00:10:23.999750900".replace( " " , "T" ) // Replace SPACE in middle with `T` to comply with ISO 8601 standard format.
)
;

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. No need to ever use Timestamp again as of JDBC 4.2 and later.

myPreparedStatement.setObject( … , instant ) ;

And retrieval.

Instant instant = myResultSet.getObject( … , Instant.class ) ;

OffsetDateTime

Support for Instant is not mandated by the JDBC specification, but OffsetDateTime is. So if the above code fails with your JDBC driver, use the following.

OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ; 
myPreparedStatement.setObject( … , odt ) ;

And retrieval.

Instant instant = myResultSet.getObject( … , OffsetDateTime.class ).toInstant() ;

If using an older pre-4.2 JDBC driver, you can use toInstant and from methods to go back and forth between java.sql.Timestamp and java.time. These new conversion methods were added to the old legacy classes.

Table of date-time types in Java (both legacy and modern) and in standard SQL


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, Java SE 10, and later

    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.



Related Topics



Leave a reply



Submit