或者只知道系统时钟和服务器之间的偏移量?如果我的系统时钟因时区而与服务器不同,会发生什么情况?谢谢
发布于 2016-11-30 10:22:12
Java没有直接设置系统时钟的API。这可以在从Java类调用的C/C++本机代码中完成,但需要管理员权限才能执行。
有一些Java库可以计算本地系统时钟和远程Apache Commons Net服务器之间的时钟偏移,比如NTP项目。这提供了计算偏移量而不同步本地时钟的代码。要实际同步,建议使用NTP客户端/服务器执行此操作。几乎所有平台(Windows、Mac、Linux等)都有NTP实施
Java库和NTP服务使用基于UTC的时间,因此时区设置不起作用。
示例:
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();请注意,本地时钟偏移(或时间漂移)是根据此标准NTP方程相对于本地时钟和NTP服务器的时钟计算的。
LocalClockOffset = ((ReceiveTimestamp - OriginateTimestamp) +
(TransmitTimestamp - DestinationTimestamp)) / 2https://stackoverflow.com/questions/40540207
复制相似问题