The Java code gets the NTP server time, And the java code gets the ntp
The apache commons-net package contains ntp-related implementation classes, including:
1 |
org.apache.commons.net.ntp.NTPUDPClient |
?
1 |
org.apache.commons.net.ntp.TimeInfo |
Related methods in NTPUDPClient:
?
1 |
TimeInfo getTime(InetAddress host, int port) throws IOException |
?
1 |
TimeInfo getTime(InetAddress host) throws IOException |
The second overload method uses the Protocol Specification default port 123.
Java code segment:
?
123456789101112131415 |
public static void main(String[] args) throws IOException { try { NTPUDPClient timeClient = new NTPUDPClient(); String timeServerUrl = "202.120.2.101" ; InetAddress timeServerAddress = InetAddress.getByName(timeServerUrl); TimeInfo timeInfo = timeClient.getTime(timeServerAddress); TimeStamp timeStamp = timeInfo.getMessage().getTransmitTimeStamp(); Date date = timeStamp.getDate(); System.out.println(date); DateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd hh:mm:ss" ); System.out.println(dateFormat.format(date)); } catch (UnknownHostException e) { e.printStackTrace(); } } |
The running result is:
?
12 |
Thu Dec 03 16 : 16 : 50 CST 2015 2015 - 12 - 03 04 : 16 : 50 |
Appendix: Frequently Used NTP server address with fast speed:
Ntp.sjtu.edu.cn 202.120.2.101 (address of the NTP server in the Network Center of Shanghai Jiao Tong University))
Time-a.nist.gov NIST, Gaithersburg, Maryland time-b.nist.gov 129.6.15.29 NIST, Gaithersburg, Maryland time-a.timefreq.bldrdoc.gov 13.03.4.101 NIST, Boulder, Colorado time-b.timefreq.bldrdoc.gov 13.03.4.102 NIST, Boulder, Colorado time-c.timefreq.bldrdoc.gov 13.03.4.103 NIST, Boulder, Colorado