I know that System.currentTimeMillis()
gives the time in milliseconds since the epoch and it is sensitive to the wall clock time of the system. I also know that it is not advisable to use System.currentTimeMillis()
to calculate elapsed time in a program that measures time.
Java library have provided System.nanoTime()
for that purpose.
I have two specific questions for System.currentTimeMillis()
:
Regarding accuracy, you are almost correct. On SOME Windows machines, currentTimeMillis() has a resolution of about 10ms (not 50ms).
currentTimeMillis() method returns the current time in milliseconds. The unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.
currentTimeMillis() is not monotonic. It is based on system time, and hence can be subject to variation either way (forward or backward) in the case of clock adjustments (e.g. via NTP).
nanoTime() method returns the current value of the most precise available system timer, in nanoseconds. The value returned represents nanoseconds since some fixed but arbitrary time (in the future, so values may be negative) and provides nanosecond precision, but not necessarily nanosecond accuracy.
The value returned by System.currentTimeMillis()
is the number of milliseconds that have elapsed since the epoch. This number of milliseconds is just that: a number of milliseconds.
Let's say that on a given day, your country has decided to go from 1:00 to 2:00 instantly, due to DST. Does that mean that 1 hour has elapsed between 1:00 and 2:00? No. 0 milliseconds have elapsed. Your country has simply decided that the millisecond value X was represented as 1:00, and that the millisecond X + 1 was represented at 2:00. The representation of the time doesn't change what milliseconds are.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With