为什么新的Java 8 Date Time API不具有纳秒精度? [英] Why does the new Java 8 Date Time API not have nanosecond precision?
问题描述
Java 8中新的Date Time API的一个特性应该是纳秒精度。但是,当我将当前日期时间打印到控制台时,如此
One of the features of the new Date Time API in Java 8 is supposed to be nanosecond precision. However when I print the current Date Time to the console like so
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
I only see millisecond precision: 2015-11-02T12:33:26,746000000+0100
操作系统似乎确实支持纳秒精度。当我通过终端打印当前日期时间
The operating system does seem to support nanosecond precision. When I print the current date time via the Terminal
date -Ins
我看到2015-11-02T12:33:26,746134417 + 0100
I see 2015-11-02T12:33:26,746134417+0100
我如何获得Java中的纳秒精度?我在Ubuntu 14.04上运行Oracle Java 1.8.0_66 64位
How do I get nanosecond precision in Java? I'm running Oracle Java 1.8.0_66 on Ubuntu 14.04 64-bit
推荐答案
java.time
一般的API 具有纳秒精度。例如:
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));
输出:
2015-11-02T12:38:00,123456789+0000
但是,它是 OffsetDateTime.now()
返回的时钟值返回一个只有毫秒的值。
However, it's the clock value returned by OffsetDateTime.now()
which is returning a value which only has milliseconds.
From < a href =https://docs.oracle.com/javase/8/docs/api/java/time/Clock.html =noreferrer> 时钟
在Java 8中实现:
From Clock
implementation in Java 8:
此处提供的时钟实现基于
System.currentTimeMillis()
。该方法几乎不能保证时钟的准确性。需要更精确时钟的应用程序必须使用不同的外部时钟本身实现此抽象类,例如NTP服务器。
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.
所以没有什么这里固有地不精确 - 只是使用 System.currentTimeMillis()
的 Clock
的默认实现。您可以创建自己更精确的子类。但是,您应该注意,添加更多精度而不添加更多准确度可能并不十分有用。 (有时候,它可能是......)
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 Date Time API不具有纳秒精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!