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

The LocalDate.now() relies on the SystemClock::instant() method, which uses System.currentTimeMillis(), so you won't get a more precise resolution with the default clock.

However, you could implement your own high-precision Clock and use that in conjunction with LocalDate:

LocalDate hpDate = LocalDate.now(microsecondClock);

For high-precision you could use the TickClock with microsecond ticks:

Clock microsecondClock = Clock.tick(Clock.systemUTC(), Duration.ofNanos(1000));

or subclass Clock and implement your own high precision clock, i.e. by using System.currentTimemillis() and System.nanoTime().


While your computer is able to report something more precise (but probably not accurate, at least not in wall time) than milliseconds this does not change the fact the Java per default uses a Clock based off of System.currentTimeMillis().

You must provide a more precise Clock to get values more precise than ms. That is, until Java 9.

Tags:

Java

Clock