0

I am new here:) I am developing a small app in android (java) and I need something to control the seconds elapsed between two events.

The problem with System.currentTimeMillis () is that the user of the device can change his system date for example after the first event, and so when I take the value returned by System.currentTimeMillis () after the second event, and I make the difference between the two values, this obtained difference is not valid at all.

Another option I tried was System.nanoTime (). Although the user changes his system time, the seconds count is valid. But here the problem is that if after the first event, the user switches off the device, the value returned by System.nanoTime() after the second event is not valid because with the device restart, the counter of System.nanoTime() also restarts , and therefore, the elapsed time is again not valid.

Does anybody know any method to count the seconds between two events, considering user date changes and user restarts of the device ?

Thanks in advance!

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Reb
  • 1
  • 1
  • Check out http://stackoverflow.com/questions/4442192/how-to-use-an-internet-time-server-to-get-the-time – elhefe Mar 26 '16 at 21:23
  • @Reb This has been addressed many times already on Stack Overflow. Please search thoroughly before posting. – Basil Bourque Mar 26 '16 at 22:44
  • Also a dup of [this](http://stackoverflow.com/q/32194245/642706). And [this](http://stackoverflow.com/q/33449737/642706). And [this](http://stackoverflow.com/q/31222397/642706). – Basil Bourque Mar 27 '16 at 05:50

1 Answers1

0

Since you want to avoid the errors that can be introduced by the user messing up with the system date, you cannot rely on that source for information. A reliable time (and accurate, if matters) can be obtained using the NTP (Network Time Protocol) protocol. Take a look at this question for more details about it: Java NTP client.

An alternative you may consider is, instead of finding a reliable clock to compute the date/time difference, you can check if the user has changed the system clock. A simple way would be to store the timestamp and check periodically (every second of so) if the new timestamp you get from the system clock is smaller (before) the previous one. If so, you can take action.

Community
  • 1
  • 1
Paul92
  • 8,827
  • 1
  • 23
  • 37