java. sql. How timestamp stores nanoseconds
java. sql. The timestamp constructor is as follows:
public Timestamp(long time) { super((time/1000)*1000); nanos = (int)((time%1000) * 1000000); if (nanos < 0) { nanos = 1000000000 + nanos; super.setTime(((time/1000)-1)*1000); } }
It basically takes time in milliseconds, then extracts the last three digits and makes them nanoscale So for the millisecond value 1304135631 421, I get timestamp getnanos()as 421000000. This is a simple calculation (add six zeros at the end)... It doesn't seem to be the best
A better approach might be the timestamp constructor, which takes time in nanoseconds and calculates the nanosecond value
If you run the following program, you will see the difference between the actual nanoseconds and the nanoseconds returned by the nanosecond token calculated by timestamp
long a = System.currentTimeMillis(); for(;;){ long b = System.currentTimeMillis(); Timestamp tm = new Timestamp(System.currentTimeMillis()); System.out.println(tm.getTime()); System.out.println(tm.getNanos()); System.out.println("This is actual nanos" + System.nanoTime()%1000000000); System.out.println("--------------------------"); if(b-a >= 1) break; }
So all the discussions about timestamp say that its storage time is as long as a few nanoseconds, which doesn't seem so correct isn't it?
Solution
Time in milliseconds does not represent nano time It's impossible to be more precise You should use timestamp #setnanos() to set the real nano
long timeInMillis = System.currentTimeMillis(); long timeInNanos = System.nanoTime(); Timestamp timestamp = new Timestamp(timeInMillis); timestamp.setNanos((int) (timeInNanos % 1000000000)); // ...