简体   繁体   中英

How can I get exact UTC current time stamp at time4j without usage of system timezone and system clock?

there!

I have to get the accurate current UTC time without calling a system clock or system time zone. I need to get precise UTC time via the Time4j library.

The issue that after getting UTC time via different ways there is a mismatch in accuracy with exact UTC time in particular - a mismatch in seconds. And that is critical for me.

I need to get exact UTC timestamp because of mismatch is more than 5 seconds on my machine and current UTC time. I have to transmit this timestamp into API and API in his tern updates DB. I perform some actions per seconds and real situation that I can't do this because of insufficiently accurate time.

Here some examples I've tested to get current UTC timestamp:

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");

I didn't get needed accuracy by those methods.

Is there any methods how can I get actual UTC timestamp with very high accuracy up to seconds via time4j?

Your code examples are all finally based on System.currentTimeMillis() . If you observe low accuracy using this simple clock then you can choose between two ways:

  • Follow the advise of JB Nizet to regularly synchronize your OS with an NTP server

  • Or you can use the package net.time4j.clock which contains alternative clocks.

Example:

  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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM