java - LocalDateTime.now() 在 Windows 和 Mac 机器上具有不同级别的精度

标签 java precision java-time platform

在我的 Mac 和 Windows 机器上使用 LocalDateTime.now() 创建一个新的 LocalDateTime 时,我得到了纳米 精度为 6 Mac 和我的 Windows 机器上的 nano 精度为 3。两者都在运行 jdk-1.8.0-172

  • 是否可以限制或提高其中一项的精度 机器?
  • 为什么精度实际上不同?

最佳答案

精度不同是因为LocalDateTime.now()使用系统默认值 Clock .

Obtains the current date-time from the system clock in the default time-zone.

This will query the system clock in the default time-zone to obtain the current date-time.

...

此 Javadoc 中的链接会将您带到 Clock.systemDefaultZone(),其中指出(强调 我的):

Obtains a clock that returns the current instant using the best available system clock, converting to date and time using the default time-zone.

This clock is based on the best available system clock. This may use System.currentTimeMillis(), or a higher resolution clock if one is available.

...

Java 使用哪个时钟取决于很多因素,看起来您的 Mac 计算机的时钟精度为秒,而您的 Windows 计算机的时钟精度为秒精度。我不知道有什么方法可以提高时钟的精度,但您绝对可以降低精度,以便跨平台匹配。

一种选择是按Ole V.V. does in his answer 做并使用 LocalDateTime.truncatedTo(TemporalUnit) .

另一种选择是插入您自己的 Clock 并使用 LocalDateTime.now(Clock) .如果可能的话,我会使用 Clock.tickMillis(ZoneId)因为此方法返回一个截断为毫秒的 Clock

Obtains a clock that returns the current instant ticking in whole milliseconds using the best available system clock.

This clock will always have the nano-of-second field truncated to milliseconds. This ensures that the visible time ticks in whole milliseconds. The underlying clock is the best available system clock, equivalent to using system(ZoneId).

...

Since:
9

关于java - LocalDateTime.now() 在 Windows 和 Mac 机器上具有不同级别的精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52029920/

相关文章:

java - 如何将 UTC 时间转换为其他时区 ("CST","IST")

java - 如何在 Java 8 中获取 UTC+0 日期?

java - 每个记录器的动态回退文件

java - 滚动时如何固定 PopupPanel 相对于页面的位置

c# - 将具有双属性的对象列表与 FluentAssertions 进行比较 (C#)

c - 为什么这段代码返回两个不同的值做同样的事情?

java - List<Dog> 是 List<Animal> 的子类吗?为什么 Java 泛型不是隐式多态的?

java - 理解java中的继承

javascript - 使用整数为美分的angularjs货币过滤器

java - 带缓存的 ZoneOffset 计算