java.sql.Timestamp way of storing NanoSeconds

前端 未结 4 1681
臣服心动
臣服心动 2020-12-17 22:21

java.sql.Timestamp constructor go like this:

public Timestamp(long time) {
    super((time/1000)*1000);
    nanos = (int)((time%1000) * 1000000);
    if (nan         


        
相关标签:
4条回答
  • 2020-12-17 22:28

    I like OpenJPA's implementation of TimestampHelper. It use static initializers to keep track of elapsed nanoseconds between calls to make a timestamp.

    0 讨论(0)
  • 2020-12-17 22:32

    Although it's an old post, I would like to add that the docs of Timestamp does state that it "holds fractional seconds by allowing the specification of fractional seconds to a precision of nanaoseconds". The confusing part is "hold". This seems confusing at first but if understood correctly, it actually does not state that it holds nanaoseconds value.It says it "holds" fractional value and allows it to be a "precision" of nanoseconds. Precision should be understood in terms of representation of total number of digits. So it essentially means that the part is actually fractional (still milliseconds) but is multiplied by 1000000 to represent it as nanoseconds.

    The accepted answer (by ever helpful BaluC) sums it up nicely.

    0 讨论(0)
  • 2020-12-17 22:43

    Since the introduction of java.time.*, there is a new factory method in java.sql.Timestamp: Timestamp.from(Instant.now()) will do the job (with nanoseconds precision). There is also Timestamp.toInstant() to convert it the other way around.

    0 讨论(0)
  • The time in millis does not represent the time in nanos. More precise it simply can't be. You're supposed to use Timestamp#setNanos() to set the real nanos.

    long timeInMillis = System.currentTimeMillis();
    long timeInNanos = System.nanoTime();
    
    Timestamp timestamp = new Timestamp(timeInMillis);
    timestamp.setNanos((int) (timeInNanos % 1000000000));
    
    // ...
    
    0 讨论(0)
提交回复
热议问题