I am making a distributed java app for which I need both parts of the app to run on one standard time. Since system times can be different I was thinking if java API contains some class to download time from a standard online source?
You need to use the NTP (Network Time Protocol):
http://en.wikipedia.org/wiki/Network_Time_Protocol
The following link contains some reference Java NTP Client code for interacting with an NTP server:
http://psp2.ntp.org/bin/view/Support/JavaSntpClient
Here is a code i found somewhr else.. and i am using it. this uses apache commons library.
// List of time servers: http://tf.nist.gov/service/time-servers.html
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 {
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);
}
}
pay attention .... timeInfo.getReturnTime()
does not return the current time from the timeserver
. it returns the local time when the request to the server
was made.
after calling timeInfo.computeDetails()
it's possible to get the offset by timeInfo.getOffset().
this returns the offset of the local time in millisecond.
to calculate the current time you could do something like:
...
long systemtime = System.currentTimeMillis();
Date realdate = new Date(systemtime + timeInfo.getOffset());
...
Thanks Rajendra_Prasad that's true
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);
long systemtime = System.currentTimeMillis();
timeInfo.computeDetails();
Date realdate = new Date(systemtime + timeInfo.getOffset());
System.out.println("Time from " + TIME_SERVER + ": " + time);
System.out.println("Time from " + TIME_SERVER + ": " + realdate);
System.out.println(""+time.getTime());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With