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. Suported 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 test;

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

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

public class TimeLookup {

	// List of time servers: http://tf.nist.gov/service/time-servers.html
	// Do not query time server more than once every 4 seconds
	public static final String TIME_SERVER = "time-a.nist.gov";

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

The output from running TimeLookup is shown below.

Time from time-a.nist.gov: Mon Jan 21 23:46:01 PST 2008

Further infromation about the NIST Internet Time Service (ITS) can be found at http://tf.nist.gov/service/its.htm. A list of NIST Internet Time Servers can be found at http://tf.nist.gov/service/time-servers.html. Note that you should not query a time server more than once every 4 seconds.