Find time-difference between epoch and current time

1k views Asked by At

I need to find the difference between two time values when one of them is fetched using System. currentTimeMillis() i.e. it's the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC and the other one is fetched using System.nanoTime() which implies it is current value of the running Java Virtual Machine's high-resolution time source, in nanoseconds.

How do I do this?

2

There are 2 answers

3
Bill Rawlinson On

This is not possible. You have a misunderstanding of the nanotime and its purpose.

From the documentation:

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary time (perhaps in the future, so values may be negative). This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change. Differences in successive calls that span greater than approximately 292 years (263 nanoseconds) will not accurately compute elapsed time due to numerical overflow.

0
dcsohl On

You cannot compare them; they are apples and oranges, not measured on the same scale or with respect to the same point in time. In particular, while currentTimeMillis() is milliseconds since 1/1/1970 00:00:00Z, nanoTime() is measured from... well, could be the startup time of your machine, or of your JVM, or of anything.

If you call both methods at the same time and note the correlation, you can then do similar correlations later, but that's about the only way to do it and is not guaranteed to be precise.