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

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

Leave a Comment