Java获取NTP网络时间

获取网络当前时间来代替获取系统当前时间
        搜索了一下,原来获取网络时间有一个协议:Network Time Protocol(NTP: 网络时间协议 )。 
        协议有了,那么java有没有相关实现呢。当然也有了。apache的commons-net包下面有ntp的实现。主要的类是: 

              org.apache.commons.net.ntp.NTPUDPClient      和         org.apache.commons.net.ntp.TimeInfo 
看下用法,NTPUDPClient中有方法: 
        public TimeInfo getTime(InetAddress host, int port) throws IOException 

          public TimeInfo getTime(InetAddress host) throws IOException 

package testMaven;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.net.ntp.NTPUDPClient;
import org.apache.commons.net.ntp.TimeInfo;
import org.apache.commons.net.ntp.TimeStamp;

public class GetNtpTime {

	public static void main(String[] args) {

	    try {
	        NTPUDPClient timeClient = new NTPUDPClient();
	        String timeServerUrl = "ntp.baijinshan.cn";
//	        String timeServerUrl = "ntp.aliyun.com";
	        InetAddress timeServerAddress = InetAddress.getByName(timeServerUrl);
	        TimeInfo timeInfo = timeClient.getTime(timeServerAddress);
	        TimeStamp timeStamp = timeInfo.getMessage().getTransmitTimeStamp();
	        Date ntpdate = timeStamp.getDate();
	        Date nowdate = new Date();
	        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
	        System.out.println(dateFormat.format(ntpdate));
//	        NTP时间与本地时间的毫秒差
	        System.out.println(ntpdate.getTime()-nowdate.getTime());
	        
	    } catch (UnknownHostException e) {
	        e.printStackTrace();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }		
			
	}

}

 

你可能感兴趣的:(Java)