【问题标题】:How can I get exact UTC current time stamp at time4j without usage of system timezone and system clock?如何在不使用系统时区和系统时钟的情况下在 time4j 获得准确的 UTC 当前时间戳?
【发布时间】:2018-08-19 12:51:27
【问题描述】:

那里!

我必须在不调用系统时钟或系统时区的情况下获得准确的当前 UTC 时间。我需要通过 Time4j 库获取精确的 UTC 时间。

在通过不同方式获取 UTC 时间后,尤其是准确的 UTC 时间会出现不匹配的问题 - 以秒为单位的不匹配。这对我来说至关重要。

我需要获取准确的 UTC 时间戳,因为我的机器和当前 UTC 时间不匹配超过 5 秒。我必须将此时间戳传输到他的 tern 更新数据库中的 API 和 API。由于时间不够准确,我每秒执行一些操作以及我无法执行此操作的真实情况。

以下是我为获取当前 UTC 时间戳而测试的一些示例:

Moment moment = Moment.UNIX_EPOCH;

First:
PlainTimestamp test1 = SystemClock.inZonalView("UTC").now();

Second:
Moment test2 = Moment.nowInSystemTime();

Third:
PlainTimestamp test3 = moment.toLocalTimestamp();

Forth:
PlainTimestamp test4 = Moment.nowInSystemTime().toZonalTimestamp("UTC");

我没有通过这些方法获得所需的准确性。

有什么方法可以通过 time4j 以非常高的精度获得实际的 UTC 时间戳,最高可达秒?

【问题讨论】:

  • 将您的操作系统配置为定期将其系统时间与 NTP 服务器同步。
  • @JBNizet - 或者只是将应用程序代码获取到ask an NTP server 本身。
  • @GordThompson 和 Time4J 甚至包含这样一个 SNTP-client 本身。

标签: java datetime time timestamp time4j


【解决方案1】:

您的代码示例最终都基于System.currentTimeMillis()。如果您使用这个简单的时钟观察到低精度,那么您可以选择两种方式:

  • 遵循 JB Nizet 的建议,定期将您的操作系统与 NTP 服务器同步

  • 或者您可以使用包含备用时钟的包net.time4j.clock

例子:

  SntpConnector clock = new SntpConnector("ptbtime1.ptb.de"); // ntp-server-address
  clock.connect(); // requires internet connectivity, performs the synchronization
  Moment utc = clock.currentTime()); // can be called without actual internet access

【讨论】:

  • 我听从了你关于使用 net.time4j.clock 包的建议,它对我有用。我在这个问题上挣扎了很长时间。谢谢!
  • 仅供参考,SntpConnector 结合了 SNTP 和 System.nanoTime()HttpClock 等其他时钟也需要互联网连接,并且更简单但可能也不太精确。
猜你喜欢
  • 2015-10-10
  • 2013-04-29
  • 1970-01-01
  • 2010-10-01
  • 2014-09-10
  • 1970-01-01
  • 1970-01-01
  • 2020-11-20
  • 2021-04-08
相关资源
最近更新 更多