zoukankan      html  css  js  c++  java
  • java 通过网络 ntp 获取网络时间

    需要 commons-net-3.4.jar 库。

    import org.apache.commons.net.ntp.NTPUDPClient;
    import org.apache.commons.net.ntp.TimeInfo;  
    import java.net.InetAddress;
    import java.net.UnknownHostException;
    import java.net.InetAddress.*;
    import java.util.Date;
    import java.util.Calendar;
    import org.apache.commons.net.ntp.TimeStamp;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Locale; 
    import java.io.IOException;
    
    public class t {
        public static void main(String[] args) {  
            try {  
                NTPUDPClient timeClient = new NTPUDPClient();  
                String timeServerUrl = "24.56.178.140";  
                InetAddress timeServerAddress = InetAddress.getByName(timeServerUrl);  
                TimeInfo timeInfo = timeClient.getTime(timeServerAddress);  
                TimeStamp timeStamp = timeInfo.getMessage().getTransmitTimeStamp();  
                DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");  
                System.out.println(dateFormat.format(timeStamp.getDate()));  
            } catch (UnknownHostException e) {  
                e.printStackTrace();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }

    npt服务器的地址大概有:

    http://tf.nist.gov/tf-cgi/servers.cgi

    1.cn.pool.ntp.org

    2.cn.pool.ntp.org

    3.cn.pool.ntp.org

    0.cn.pool.ntp.org

    cn.pool.ntp.org

    tw.pool.ntp.org

    0.tw.pool.ntp.org

    1.tw.pool.ntp.org

    2.tw.pool.ntp.org

    3.tw.pool.ntp.org

  • 相关阅读:
    Centos7 KVM启用嵌套虚拟化
    CentOS 桥接网卡配置
    centos iso镜像自动挂载
    git status没有颜色提示
    virt-install 安装系统和启动虚机
    Python 源代码代码打包成 whl 文件
    存储池与存储卷,使用virt-install创建虚拟机
    ftp 搭建 centos 源
    git 生成并添加 SSH key
    linked-list-cycle leetcode C++
  • 原文地址:https://www.cnblogs.com/welhzh/p/5011773.html
Copyright © 2011-2022 走看看