准确的系统时间

Accurate System time

在 java 中获得最准确系统时间(时分秒)的最佳方法是什么?我一直在研究时钟、日期和日历对象。我希望能够使用最准确的系统时间为数据包添加时间戳,并通过网络发送它(如果可能,精确到 Milli 甚至 NanoSeconds)。

如果你想获得以纳秒为单位的时间,那么使用 system.nanoTime(); 这样最好

Java 9

java.time framework supports values with up to nanosecond 决议。这意味着秒的小数部分最多九 (9) 位。

Java 9 and later, a new implementation of Clock can capture the current moment up to that nanosecond分辨率下。但是“你的里程可能会有所不同”。实际分辨率和实际精度取决于主机硬件时钟能力。

Instant instant = Instant.now();

2016-01-02T12:34:56.123456789Z

Java 8

与 Java 9 相同,java.time 类 最高支持 nanosecond 分辨率。

但当前时刻的捕获分辨率最高为 millisecond。这意味着小数秒只有三 (3) 个或更少的数字。此限制是因为用于 Clock.

的遗留实现

Java 6 & 7

旧的日期时间 类 首先与 Java 的最早版本捆绑在一起,仅支持毫秒分辨率。这包括 java.util.Datejava.util.Calendarjava.util.GregorianCalendar。这些旧的 类 也设计得很糟糕,很混乱,很麻烦。避开它们。

java.time 的大部分功能在 ThreeTen-Backport project, and further adapted to Android in the ThreeTenABP 项目中向后移植。

据我所知,这些依赖于相同的遗留实现,分辨率仅为毫秒。

准确性

Accuracy and precision 始终取决于您的主机硬件时钟能力。

查看问题,How precise is the internal clock of a modern PC?

据我了解,当今常见的计算机硬件,您不能指望以纳秒级的精度捕获当前时刻。