Get Real Time - Not Device Set Time in android
Solution 1
You need to use the NTP (Network Time Protocol) protocol:
Here is some code I found somewhere else... and I am using it. This uses the Apache Commons library, which can be installed using Gradle (adding a dependency on commons-net:commons-net:3.6
)
If you need a list of time servers, check: http://tf.nist.gov/service/time-servers.html
Here is some Java Code for you to use:
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);
}
}
Note the Android code must run on the background thread and include gradle dependency:
implementation 'commons-net:commons-net:3.6'
Solution 2
There is no Android API to get you such a time. The user can always change the device time, nothing you can do about that.
Your best bet would be to run a server with a webservice, from which you can get the time. Since you control the server, you can try to ensure it returns the correct time.
Comments
-
Ashish Dwivedi almost 2 years
How to find out the Real Geographical Time, as in my application I want to attach the real time with my application.
So that if the user changes the time in his device then I should get only the real prevailing time - NOT THE DEVICE TIME
My question is much confusing but try to understand in a simple language -
I dont want DEVICE TIME, I want REAL PREVAILING TIME at any instant
-
androidevil over 8 yearsIn my case, the valid timestamp was found using: timeInfo.getMessage().getReceiveTimeStamp().getTime()
-
Stefano over 7 yearslong returnTime = timeInfo.getMessage().getReceiveTimeStamp().getTime();
-
Prashanth Debbadwar over 7 yearscan we use joda time lib?
-
Opiatefuchs over 6 yearsolder post, but it´s important here: Stefano is right. If getting time like showed in the post, it returns (described in API) ...time message packet was received by local machine . It seems that this returns the device time, I tried it. But if you use
timeInfo.getMessage().getReceiveTimeStamp().getTime()
, you get (described in API) ...the receive time as defined in RC_1305 which is the net time no matter what is defined in device.. -
f.trajkovski about 5 yearsEven if you use this method, changing the time on the phone will cause the NTPUDPClient to give you that time instead of the time from the host.