chocospaz
chocospaz

Reputation: 749

Get Accurate UTC Time in Android

Okay so this might be basic but unfortunately I haven't found anything yet to help with this.

I'd like certain functionality to only happen in Android during a time frame that is specific to UTC/GMT Time.

How do you do this? I tried using System.currentTimeMillis() but if you change the time on an Android Device in the settings, this will also change System.currentTimeMillis().

I'd like to grab a time that is equal to UTC/GMT AND is independent of the Android Device Settings clock, so if the clock is changed on the device it won't interfere.

Any thoughts?

Thanks! Christopher Steven

Upvotes: 2

Views: 1813

Answers (3)

Genkus
Genkus

Reputation: 181

System.nanoTime() returns the number of nanoseconds since the start up time, and is therefore not be susceptible to system clock changes.

At the startup use:

long startTime = System.TimeInMillis();
long nanoToDeduct = System.nanoTime();

Then at any point in time you can get the current time of the program as the clock was set at the startup of the program with

long currentTime = startTime - timeToDeduct + System.nanoTime();

Upvotes: 0

Matter Cat
Matter Cat

Reputation: 1578

time.nist.gov is your friend if you want a truly accurate time.*

                String TIME_SERVER = "time.nist.gov";
                NTPUDPClient timeClient = new NTPUDPClient();
                InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
                TimeInfo timeInfo = timeClient.getTime(inetAddress);
                NtpV3Packet message = timeInfo.getMessage();

                //get the utc long from the server
                long serverTime = message.getTransmitTimeStamp().getTime();

(Be sure to bundle all this in a thread if you're running on Android!)

One thing that I like to do is to take the difference between the server time and system time and store that for future use. In short, as long as the system time isn't fiddled with, you don't have to do multiple time calls. You can just take system time and change it based on the difference.

*you will need apache commons for this to work.

Upvotes: 4

chengpohi
chengpohi

Reputation: 14227

You need a time service from Internet. you can get the real time from time server NIST

apache-commons has a TimeInfo class to get NTP date

Example: NTPClient

Upvotes: 0

Related Questions