Java.sql.Timestamp way to store NanoSeconds

The constructor of java.sql.Timestamp looks like this:

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 and then extracts the last 3 digits and makes it a sediment. So, for the millisecond value of 1304135631 421 , I get Timestamp.getnanos () as 421000000 . This is a simple calculation (adding 6 zeros at the end) ... does not seem optimal.

A better way could be the Timestamp constructor, which takes time in nanoseconds and then calculates the nanosecond value.

If you run the program below, you will see the difference between the actual nanoseconds and the one returned by the Timestamp method for calculating nanoscopes.

 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(ba >= 1) break; } 

So, the whole discussion about Timestamp, which says that it stores time to nanoseconds, does not seem so right. Not?

+6
source share
4 answers

Time in millise does not represent time in nano. More precisely, this simply cannot be. You must use Timestamp#setNanos() to set real nano.

 long timeInMillis = System.currentTimeMillis(); long timeInNanos = System.nanoTime(); Timestamp timestamp = new Timestamp(timeInMillis); timestamp.setNanos((int) (timeInNanos % 1000000000)); // ... 
+6
source

With the introduction of java.time.* , A new factory method has appeared in java.time.* : Timestamp.from(Instant.now()) will do the job (accurate to the nanosecond). There is also Timestamp.toInstant() to convert it the other way around.

+1
source

Although this is an old post, I would like to add that the Timestamp docs state that it "contains fractional seconds, allowing the specification of fractional seconds to the accuracy of nanaoseconds". The confusing part is "hold." At first it seems confusing, but if understood correctly, it doesnโ€™t actually claim that it contains a nanaoseconds value. It says that it โ€œholdsโ€ a fractional value and allows it to be โ€œprecisionโ€ nanoseconds. Accuracy should be understood in terms of representing the total number of digits. Thus, this essentially means that the part is actually fractional (another milliseconds), but is multiplied by 1,000,000 to represent it as nanoseconds.

The accepted answer (the ever useful BaluC) summarizes it well.

0
source

I like the OpenJPA TimestampHelper implementation. It uses static initializers to track the elapsed nanoseconds between calls to create a timestamp.

0
source

Source: https://habr.com/ru/post/886994/


All Articles