Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the current network time on Android [duplicate]

I've noticed that System.currentTimeMillis() time is device dependent. If I change the time on the device's clock, this method will return a different answer.

For example: If the real time now is 10:00, and I change the clock on my device to 9:30, then System.currentTimeMillis() will return the 9:30 time (in milliseconds..).

I've also tried this answer and some other answers, but didn't find anything useful. I should state that my app works mostly offline. Is there a way to get the real current time (device independent) without external API?

like image 927
Aviv Ben Shabat Avatar asked May 11 '26 14:05

Aviv Ben Shabat


1 Answers

If it were not for the 'offline' part, I'd have suggested to use a time server, but given that your app is offline most of the time that might not be a good solution.

If you don't need the actual time but just a time that cannot be messed with, you can use SystemClock.elapsedRealtime() which gives you the time since the device last booted.

You could also combine time server and SystemClock.elapsedRealtime(): Fetch the time from timer server once (e.g. after bootup) and from then on add elapsedRealtime() to that initial value (minus the elapsedRealtime value of when you get the timerserver value).

like image 180
Ridcully Avatar answered May 14 '26 05:05

Ridcully