12

If I use System.currentTimeMillis() at 00:00 and I get X value.

Then I set the clock back one hour, and after one hour i call System.currentTimeMillis().

Will it return X again, or will it just be X + 3600 * 1000

Twinone
  • 2,949
  • 4
  • 28
  • 39
  • According to the javadoc, it returns *the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.* => so you can expect it to be adjusted if you change the clock of your computer. – assylias Mar 25 '13 at 16:58
  • 2
    No guarantees, I believe. On different systems the JDK must jump through different hoops to get system time, and may not always be immediately responsive to system clock changes. – Hot Licks Mar 25 '13 at 16:59

3 Answers3

13

In a nutshell, whenever you change system time, the value returned by System.currentTimeMillis() will change accordingly.

This is in contrast to System.nanoTime().

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • I knew about the nanoTime(), but I read that it was 20 times more expensive than currentTimeMillis, so I'd prefer to avoid that. I don't need much precision (half a second error may be perfectly good). Are there any alternatives or should I just use nanoTime? – Twinone Mar 25 '13 at 17:09
  • @TwinOneAndroid 20 times a few cpu cycles is still not much, unless you call it thousands of times per second... More about it [here](https://blogs.oracle.com/dholmes/entry/inside_the_hotspot_vm_clocks). – assylias Mar 25 '13 at 17:17
  • 2
    @TwinOneAndroid For measuring *time spans*, I believe you should **always** use `nanoTime()`. (Can't remember the exact reason why, something to do with the system time behaving counterintuitively in some respects. So take this with a grain of salt.) – millimoose Mar 25 '13 at 17:47
  • 2
    The point of nanoTime() is that it *doesn't* change when the system clock is somehow adjusted, so two timestamps taken some time apart will correctly reflect that timespan, regardless of clock adjustments. – Hot Licks Mar 25 '13 at 18:23
  • 1
    @HotLicks Another issue is that the granularity of `currentTimeMillis()` is OS-dependent, whereas practically, `nanoTime()` should have a resolution under 1ms. (Going by https://code.google.com/p/javasimon/wiki/SystemTimersGranularity ) – millimoose Mar 25 '13 at 19:53
  • But when the clocks change (Daylight Savings / Summer Time etc), the time in UTC doesn't change, no? So the currentTimeMillis() should not jump back or forward no? – Andrew Mackenzie Oct 28 '13 at 12:06
1

It will return X because System.currentTimeMillis() returns the number of milliseconds since the epoch. That means it will be insynch with your clock and count the number of seconds since January 1, 1970 UTC

Oleksi
  • 12,947
  • 4
  • 56
  • 80
1

On Android, you can always use SystemClock.elapsedRealtime().

jpmcosta
  • 1,752
  • 15
  • 24