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

上一篇:Yii源码阅读笔记(二十一)——请求处理流程


下一篇:POJ 1141 Brackets Sequence