在我的 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/