Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.out of nanoTime is incorrect?

Tags:

java

time

I'm doing a private Timestamp timestamp = new Timestamp(System.nanoTime()); in one of my entities when the object is created.

If I system.out the timestamp, I'm getting values like;

2282-08-24 11:25:00.506
2286-04-16 01:47:35.882

What is wrong here?

System.currentTimeMillis() gives the correct date, but I need more accuracy. What could be wrong here??

like image 523
membersound Avatar asked Dec 21 '22 14:12

membersound


2 Answers

System.nanoTime() is a completely abstract way of measuring time, it has something to do with the number of CPU cycles since the computer was started. It's completely unrelated to java.util.Date that uses epoch time (number of milliseconds since 1970).

You are free to compare two different values of System.nanoTime() to get very accurate time measurements (theoretically up to 1 nanosecond), but the absolute value taken alone is useless.

like image 142
Tomasz Nurkiewicz Avatar answered Jan 01 '23 23:01

Tomasz Nurkiewicz


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 origin time (perhaps in the future, so values may be negative). The same origin is used by all invocations of this method in an instance of a Java virtual machine; other virtual machine instances are likely to use a different origin.

documentation

like image 29
McDowell Avatar answered Jan 01 '23 23:01

McDowell