获取ntp时间-java-ntp.aliyun.com
- 协议:Network Time Protocol(NTP: 网络时间协议 )
- pom:commons-net
- 主要的类是:
- org.apache.commons.net.ntp.NTPUDPClient
- org.apache.commons.net.ntp.TimeInfo
try {
NTPUDPClient timeClient = new NTPUDPClient();
String timeServerUrl = "ntp.aliyun.com";
InetAddress timeServerAddress = InetAddress.getByName(timeServerUrl);
TimeInfo timeInfo = timeClient.getTime(timeServerAddress);
TimeStamp timeStamp = timeInfo.getMessage().getTransmitTimeStamp();
Date ntpdate = timeStamp.getDate();
Date nowdate = new Date();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
System.out.print("ntp时间:");
System.out.println(dateFormat.format(ntpdate));
System.out.print("本地时间戳:");
System.out.println(nowdate.getTime());
System.out.print("ntp时间戳:");
System.out.println(ntpdate.getTime());
// NTP时间与本地时间的毫秒差
System.out.print("NTP时间与本地时间的毫秒差:");
System.out.println(ntpdate.getTime()-nowdate.getTime());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}