【问题标题】:Error in getting Time Server - Java获取时间服务器时出错 - Java
【发布时间】:2013-10-01 04:44:32
【问题描述】:

我正在使用以下代码从在线服务器获取时间:

我已包含以下标题

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

这是我的主要代码

        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.getMessage().getTransmitTimeStamp().getTime();
Date time = new Date(returnTime);
System.out.println("" + time);

        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    // End of variables declaration                   
}

但问题是,这段代码返回了我在本地机器上设置的时间,而不是来自服务器的时间。!!!

【问题讨论】:

  • @MattJones 先生,还是同样的问题!
  • 现在我很感兴趣......让我试一试
  • @MattJones 注意,先生,我想要印度标准时间
  • @MattJones 对不起先生,我说错了,它确实需要时间从互联网上,但现在甚至传输一个正在工作,但问题是我总是希望它显示格林威治时间,但它显示根据机器上设置的区域;因为如果有人改变他们的时区,时间就会改变所以我想要格林威治标准时间我现在不知道它是如何突然开始工作的
  • @MattJones 顺便说一句,非常感谢您的帮助

标签: java time ntp


【解决方案1】:

试试这样的?

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.getMessage().getTransmitTimeStamp().getTime();
Date time = new Date(returnTime);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-21
    • 2016-12-28
    • 2021-03-05
    • 2013-01-24
    • 2015-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多