为什么新的 Java 8 Date Time API 没有纳秒精度? [英] Why does the new Java 8 Date Time API not have nanosecond precision?

查看:15
本文介绍了为什么新的 Java 8 Date Time API 没有纳秒精度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 8 中新的日期时间 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 64 位上运行 Oracle Java 1.8.0_66

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.

来自时钟 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆