Java获取网络时间

转载自 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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用Java中的`java.net.URL`和`java.HttpURLConnection`类来获取网络时间。以下是一个示例代码: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class NetworkTimeExample { public static void main(String[] args) { try { // 创建URL对象 URL url = new URL("http://www.baidu.com"); // 打开URL连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置请求方式为GET connection.setRequestMethod("GET"); // 获取响应码 int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // 读取响应内容 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); // 解析响应内容提取时间信息 String timeStr = response.toString(); // 假设响应内容包含时间信息 // 进行时间解析和处理 System.out.println("网络时间:" + timeStr); } else { System.out.println("获取网络时间失败,响应码:" + responseCode); } // 关闭连接 connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } ``` 这个例子通过发送一个GET请求到百度网址(http://www.baidu.com),然后获取到响应内容并解析出时间信息。您可以根据自己的需求修改URL地址和解析方式。注意,这种方法获取的是服务器的时间,而不是本地时间
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值