首页 > 解决方案 > 使用ntp获取网络时间服务器

问题描述

我正在尝试在 Net-beans IDE 8.2 上使用 ntp 从互联网上获取时间。我没有收到错误,但程序继续运行而不显示时间。

我已经在库中添加了 commons-net-3.6.jar。我错过了什么吗?

请在下面查看我的代码。我已从以下代码中获取此代码:如何使用 Internet 时间服务器获取时间?

package timelookup;
import java.util.Date;
import java.net.InetAddress;
import org.apache.commons.net.ntp.NTPUDPClient;
import org.apache.commons.net.ntp.TimeInfo;

public class TimeLookup {
    public static void main(String[] args)throws Exception {
       String TIME_SERVER = "time-a.nist.gov";   
        NTPUDPClient timeClient = new NTPUDPClient();
        InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
        TimeInfo timeInfo = timeClient.getTime(inetAddress);
        long returnTime = timeInfo.getReturnTime();
        Date time = new Date(returnTime);
        System.out.println("Time from " + TIME_SERVER + ": " + time);
    }

}

标签: javantp

解决方案


推荐阅读