How do I query the NIST Internet Time Service using the Network Time Protocol?
Author: Deron Eriksson
Description: This Java tutorial describes how to query the NIST Internet Time Service using the Network Time Protocol (NTP).
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)


The ApacheSW Commons NetS library is a great library for writing client software to communicate with various types of network servers. Supported protocols include FTPW, NNTP, Telnet, WhoisW, and NTP. The TimeLookup class below shows how to use Common Net's NTPUDPClient class to query an NIST Internet Time Service server and get back a long representing a standard JavaSW time.

TimeLookup.java

package demo;

import java.net.InetAddress;
import java.util.Date;

import org.apache.commons.net.ntp.NTPUDPClient;
import org.apache.commons.net.ntp.NtpV3Packet;
import org.apache.commons.net.ntp.TimeInfo;

public class TimeLookup {

	// List of time servers: http://tf.nist.gov/tf-cgi/servers.cgi
	// Do not query time server more than once every 4 seconds
	public static final String TIME_SERVER = "nist1-ny.ustiming.org";

	public static void main(String[] args) throws Exception {
		NTPUDPClient timeClient = new NTPUDPClient();
		InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
		TimeInfo timeInfo = timeClient.getTime(inetAddress);
		NtpV3Packet message = timeInfo.getMessage();
		long serverTime = message.getTransmitTimeStamp().getTime();
		Date time = new Date(serverTime);
		System.out.println("Time from " + TIME_SERVER + ": " + time);
	}
}

The output from running TimeLookup is shown below.

Time from nist1-ny.ustiming.org: Wed Jun 19 12:56:17 PDT 2013

Further information about the NIST Internet Time Service (ITS) can be found at http://www.nist.gov/pml/div688/grp40/its.cfm. A list of NIST Internet Time Servers can be found at http://tf.nist.gov/tf-cgi/servers.cgi. Note that you should not query a time server more than once every 4 seconds.