Reputation: 197
Or it is only to know the offset between the system clock and the server? If my system's clock is different from the server because of the time zone what happens? thanks
Upvotes: 1
Views: 2783
Reputation: 23738
Java doesn't have an API to set system clock directly. This could be done in C/C++ native code called from your Java classes but would require administrative rights to execute.
There are some Java libraries such as Apache Commons Net project that can compute the clock offset between the local system clock and a remote NTP server. This provides the code to calculate the offset not sync the local clock. To actually sync, recommend to do this using a NTP client/server. There are NTP implementations for nearly all platforms (Windows, Mac, Linux, etc.)
The Java library and NTP services use times based on UTC so time zone settings have no effect.
Example:
NTPUDPClient client = new NTPUDPClient();
client.open();
// use host name or IP address of target NTP server
InetAddress hostAddr = InetAddress.getByName("pool.ntp.org");
TimeInfo info = client.getTime(hostAddr);
info.computeDetails(); // compute offset/delay if not already done
Long offsetValue = info.getOffset();
Long delayValue = info.getDelay();
String delay = (delayValue == null) ? "N/A" : delayValue.toString();
String offset = (offsetValue == null) ? "N/A" : offsetValue.toString();
System.out.println(" Roundtrip delay(ms)=" + delay
+ ", clock offset(ms)=" + offset); // offset in ms
client.close();
Note that the local clock offset (or time drift) is calculated with respect to the local clock and the NTP server's clock according to this standard NTP equation.
LocalClockOffset = ((ReceiveTimestamp - OriginateTimestamp) +
(TransmitTimestamp - DestinationTimestamp)) / 2
Upvotes: 2