为什么新的 Java 8 Date Time API 没有纳秒精度?

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

Java 8 中新日期时间 API 的功能之一应该是纳秒精度。但是,当我像这样将当前日期时间打印到控制台时

DateTimeFormatter formatter = DateTimeFormatter
    .ofPattern("yyyy-MM-dd'T'HH:mm:ss,nnnnnnnnnZ");
System.out.println(OffsetDateTime.now().format(formatter)); 

我只看到毫秒精度:2015-11-02T12:33:26,746000000+0100

操作系统似乎支持纳秒精度。当我通过终端打印当前日期时间时

date -Ins

我看到 2015-11-02T12:33:26,746134417+0100

如何在 Java 中获得纳秒精度?我是 运行 Oracle Java 1.8.0_66 Ubuntu 14.04 64 位

java.time API 通常 具有纳秒精度。例如:

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

输出:

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

但是,OffsetDateTime.now()返回的时钟值是返回一个只有毫秒的值。

来自 Clock 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.

所以这里没有任何本质上不精确的地方 - 只是 Clock 使用 System.currentTimeMillis() 的默认实现。您可能会创建自己的更精确的子类。但是,您应该注意,在不增加 accuracy 的情况下增加精度可能不是很有用。 (诚​​然,有时候可能是...)

为了对 Jon Skeet 的回答做出重要补充,Java 9 应该提供精度更高的时钟 - 请参阅 the bug log。背景:在许多操作系统上(尤其是Linux),有更好的时钟可用。

The Java SE 8 specification for java.time.Clock states that "The system factory methods provide clocks based on the best available
system clock. This may use System.currentTimeMillis(), or a higher resolution clock if one is available.". In JDK 8 the implementation
of the clock returned was based on System.currentTimeMillis(), and thus has only a millisecond resolution. In JDK 9, the implementation
is based on the underlying native clock that System.currentTimeMillis() is using, providing the maximum resolution available from that clock. On most systems this can be microseconds, or sometimes even tenth of microseconds.

An application making the assumption that the clock returned by these system factory methods will always have milliseconds precision and actively depends on it, may therefore need to be updated in order to take into account the possibility of a greater resolution, as was
stated in the API documentation.

还应注意(奇特的)事实,秒精度在闰秒附近不存在 - 即使在 Java 9.