java 计时 纳秒,为什么新的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));

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

I see 2015-11-02T12:33:26,746134417+0100

How do I get nanosecond precision in Java? I'm running Oracle Java 1.8.0_66 on Ubuntu 14.04 64-bit

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值