需要 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