在 java项目 中,你可以使用 NTP(Network Time Protocol) 获取服务器时间。最常用的方法是使用 Apache Commons Net 库,或者直接用 Java 自带的 InetAddress
进行 NTP 请求。
方法 1:使用 Apache Commons Net 库
✅ 推荐: 这种方式更稳定,官方支持 NTP 协议
1. 添加 Maven 依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-net</artifactId>
<version>3.9.0</version> <!-- 选择最新版本 -->
</dependency>
2. 代码获取 NTP 时间
import org.apache.commons.net.ntp.NTPUDPClient;
import org.apache.commons.net.ntp.TimeInfo;
import java.net.InetAddress;
import java.util.Date;
public class NtpTimeFetcher {
public static Date getNtpTime(String ntpServer) {
NTPUDPClient client = new NTPUDPClient();
client.setDefaultTimeout(5000); // 超时时间 5s
try {
InetAddress hostAddr = InetAddress.getByName(ntpServer);
TimeInfo timeInfo = client.getTime(hostAddr);
timeInfo.computeDetails();
long ntpTime = timeInfo.getMessage().getTransmitTimeStamp().getTime