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();
	    }		
			
	}

}

 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值