Java 8 Instant.Now() with Nanosecond Resolution

How are nanoseconds calculated in java.time.Instant?

The Instant class just promises nanosecond precision (i.e. the value of nanos will be provided in nanoseconds). It does not promise nanosecond accuracy (i.e. the value may not accurately represent the current number of nanoseconds).

A simple multiplier (as specified by the specific SystemClock class instance used) is all that is needed to convert whatever unit can be obtained to nanoseconds.


Other points:

The System.currentTimeMillis method's documentation you link does not say 'at best'; it just promises to do as well as it can.

Secondly, you can see the implementation of the method by following through the stack trace in (for example) Instant.now(). On my machine's java 8 setup (Mac OS, JDK 1.8.0.241) this falls back to using the SystemClock class, which eventually uses System.currentTimeMillis() and Instant.ofEpochMillis. In that method, you can see that it simply multiplies the 'epoch millis' by 1_000_000.

This has changed in later versions of java however.

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 the Oracle & OpenJDK implementations of Java 8/9. 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….

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...)

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.



Related Topics



Leave a reply



Submit