How to use an Internet time server to get the time?

Rakesh Juyal picture Rakesh Juyal · Dec 14, 2010 · Viewed 43.8k times · Source

I would like to get the GMT [ Greenwich Mean Time ], and also I don't want to rely on my system date time for that. Basically, I want to use time sync server like in.pool.ntp.org [ India ] for GMT calculation, or may be I am going in wrong direction!

How to do this in java ?

Is there any java library to get time from Time server?

Answer

aikikode picture aikikode · Jan 16, 2013

sp0d is not quite right:

timeInfo.getReturnTime(); // Returns time at which time message packet was received by local machine

So it just returns current system time, not the received one. See TimeInfo man page.
You should use

timeInfo.getMessage().getTransmitTimeStamp().getTime();

instead.
So the code block will be:

String TIME_SERVER = "time-a.nist.gov";   
NTPUDPClient timeClient = new NTPUDPClient();
InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
TimeInfo timeInfo = timeClient.getTime(inetAddress);
long returnTime = timeInfo.getMessage().getTransmitTimeStamp().getTime();
Date time = new Date(returnTime);