2

I ran a simple test to create a million time objects and tested the following

 int nano = new Timestamp(new Date().getTime()).getNanos();
 if((nano & 0x00000000003F) != 0x0) {
    System.out.println("Nano from timestamp : " +  nano);
 }

Nothing was output implying that the last least significant 6 digits were all zeros. So does the Timestamp merely depend on the value as returned from System.currentTimeMillis() and just multiply it with 1000000 ?

Is the Timestamp useful with nanosecond precision? In the current case, since I am not getting any non-zero value, it implies that the precision is just reduced to milliseconds (and not nanoseconds).

So what's the benefit of using Timestamp?

Sirish Renukumar
  • 1,509
  • 2
  • 13
  • 16

1 Answers1

4

The type java.sql.Timestamp has nanosecond precision using a separate field, as documented:

Note: This type is a composite of a java.util.Date and a separate nanoseconds value. Only integral seconds are stored in the java.util.Date component. The fractional seconds - the nanos - are separate.

You are setting the timestamp value using java.util.Date.getTime(), which provides only millisecond precision: "Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object."; the subsecond value of that millisecond value is stored in the nanos field, in other words, the submillisecond value of nanos is zero this way.

If you want to use the nanosecond precision, you need to set and get the nanos separately (using setNanos and getNanos), or you need to construct it from a type that does have nanosecond precision (java.time.LocalDateTime) using Timestamp.valueOf(java.time.LocalDateTime).

Given that nanos stores all of the fractional seconds, using setNanos has some caveats, see also some of the answers to java.sql.Timestamp way of storing NanoSeconds

This said, you will only get benefit from this nanosecond precision if the database you use actually supports it. For example I maintain the JDBC driver for Firebird, and Firebird supports only 100 microsecond precision, not nanosecond precision, and PostgreSQL for example supports microsecond precision.

Community
  • 1
  • 1
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197