The Java code gets the NTP server time, And the java code gets the ntp

Source: Internet
Author: User

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 20152015-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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.