Java读取NTP服务器时间
Eave
2025.03.12
在Java项目中,你可以使用NTP(Network Time Protocol)获取服务器时间。最常用的方法是使用Apache Commons Net库,或者直接用Java自带的InetAddress进行NTP请求。
使用Apache Commons Net库
1.添加Maven依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-net</artifactId>
<version>3.9.0</version>
</dependency>
2.代码获取NTP时间
package com.wizardaws.tools.application;
import org.apache.commons.net.ntp.NTPUDPClient;
import org.apache.commons.net.ntp.TimeInfo;
import java.net.InetAddress;
import java.util.Date;
public class NtpClient
{
public static void main(String[] args)
{
String ntpServer = "ntp.ntsc.ac.cn"; // NTP服务器地址 国家授时中心
NTPUDPClient client = new NTPUDPClient();
client.setDefaultTimeout(5000);
try
{
InetAddress inetAddress = InetAddress.getByName(ntpServer);
TimeInfo timeInfo = client.getTime(inetAddress);
Date date = timeInfo.getMessage().getTransmitTimeStamp().getDate();
ZonedDateTime zonedDateTime = date.toInstant().atZone(ZoneId.systemDefault());
System.out.println("NTP Time: " + date);
System.out.println("NTP Time: " + zonedDateTime);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
client.close();
}
}
}
结果输出如下:
NTP Time: Wed Mar 12 10:42:17 CST 2025
NTP Time: 2025-03-12T10:42:17.515+08:00[Asia/Shanghai]