Java获取网络时间

来源:互联网 发布:智能马桶圈 知乎 编辑:程序博客网 时间:2024/05/18 01:30

转载自 http://brokendreams.iteye.com/blog/1840603


获取网络时间有一个协议:Network Time Protocol(NTP: 网络时间协议 )。 

        协议有了,那么java有没有相关实现呢。当然也有了。apache的commons-net包下面有ntp的实现。主要的类是: 
Java代码  收藏代码
  1. org.apache.commons.net.ntp.NTPUDPClient  

和 
Java代码  收藏代码
  1. org.apache.commons.net.ntp.TimeInfo  

看下用法,NTPUDPClient中有方法: 
Java代码  收藏代码
  1. public TimeInfo getTime(InetAddress host, int port) throws IOException  

和 
Java代码  收藏代码
  1. public TimeInfo getTime(InetAddress host) throws IOException  

第二个重载方法是用协议规范默认端口:123。 

看下具体实现代码: 
Java代码  收藏代码
  1. /*** 
  2.      * Retrieves the time information from the specified server and port and 
  3.      * returns it. The time is the number of miliiseconds since 
  4.      * 00:00 (midnight) 1 January 1900 UTC, as specified by RFC 1305. 
  5.      * This method reads the raw NTP packet and constructs a <i>TimeInfo</i> 
  6.      * object that allows access to all the fields of the NTP message header. 
  7.      * <p> 
  8.      * @param host The address of the server. 
  9.      * @param port The port of the service. 
  10.      * @return The time value retrieved from the server. 
  11.      * @exception IOException If an error occurs while retrieving the time. 
  12.      ***/  
  13.     public TimeInfo getTime(InetAddress host, int port) throws IOException  
  14.     {  
  15.         // if not connected then open to next available UDP port  
  16.         if (!isOpen())  
  17.         {  
  18.             open();  
  19.         }  
  20.   
  21.         NtpV3Packet message = new NtpV3Impl();  
  22.         message.setMode(NtpV3Packet.MODE_CLIENT);  
  23.         message.setVersion(_version);  
  24.         DatagramPacket sendPacket = message.getDatagramPacket();  
  25.         sendPacket.setAddress(host);  
  26.         sendPacket.setPort(port);  
  27.   
  28.         NtpV3Packet recMessage = new NtpV3Impl();  
  29.         DatagramPacket receivePacket = recMessage.getDatagramPacket();  
  30.   
  31.         /* 
  32.          * Must minimize the time between getting the current time, 
  33.          * timestamping the packet, and sending it out which 
  34.          * introduces an error in the delay time. 
  35.          * No extraneous logging and initializations here !!! 
  36.          */  
  37.         TimeStamp now = TimeStamp.getCurrentTime();  
  38.   
  39.         // Note that if you do not set the transmit time field then originating time  
  40.         // in server response is all 0's which is "Thu Feb 07 01:28:16 EST 2036".  
  41.         message.setTransmitTime(now);  
  42.   
  43.         _socket_.send(sendPacket);  
  44.         _socket_.receive(receivePacket);  
  45.   
  46.         long returnTime = System.currentTimeMillis();  
  47.         // create TimeInfo message container but don't pre-compute the details yet  
  48.         TimeInfo info = new TimeInfo(recMessage, returnTime, false);  
  49.   
  50.         return info;  
  51.     }  

       大概过程就是想目标网络地址发包来获取网络时间,具体细节由协议来规范。 
所以我们还需要来确定网络地址,继续搜索,发现网络上有时间服务器,也叫授时服务器。我们的用智能手机的时间是不是通过这种方式来同步的呢? 
       找到了这样一些服务器地址: 
中国时间网 
       国外的 
NIST Internet Time Servers 

代码例子: 
Java代码  收藏代码
  1. public static void main(String[] args) {  
  2.     try {  
  3.         NTPUDPClient timeClient = new NTPUDPClient();  
  4.         String timeServerUrl = "time-a.nist.gov";  
  5.         InetAddress timeServerAddress = InetAddress.getByName(timeServerUrl);  
  6.         TimeInfo timeInfo = timeClient.getTime(timeServerAddress);  
  7.         TimeStamp timeStamp = timeInfo.getMessage().getTransmitTimeStamp();  
  8.         DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");  
  9.         System.out.println(dateFormat.format(timeStamp.getDate()));  
  10.     } catch (UnknownHostException e) {  
  11.         e.printStackTrace();  
  12.     } catch (IOException e) {  
  13.         e.printStackTrace();  
  14.     }  
  15. }  


输出:
Java代码  收藏代码
  1. 2013-04-02 11:01:08  


可调整本机时间,然后观察输出是否正确。
0 0
原创粉丝点击