Timestamp存储NanoSeconds的方式

Timestamp存储NanoSeconds的方式

本文介绍了java.sql.Timestamp存储NanoSeconds的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java.sql.Timestamp构造函数如下:

java.sql.Timestamp constructor go 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);
    }
}

它基本上接受以毫秒为单位的时间然后提取最后一个3位数,使其成为纳米级。因此,对于毫秒值1304135631 421 ,我将Timestamp.getnanos()作为
421000000 。这是简单的计算(最后加上6个零)......似乎不是最佳的。

It basically accepts time in millisecond and then extracts the last 3 digits and makes it nanos. So for a millisecond value of 1304135631 421, I'm getting Timestamp.getnanos() as421000000. This is plain calculation (adding 6 zeroes at the end)... does not seems to be optimum.

更好的方法可能是Timestamp构造函数接受纳秒的时间,然后计算纳秒值。

A better way could have been Timestamp constructor that accepts time in nanoseconds and then calculates the nanosecond value out of that.

如果您运行以下程序,您将看到实际纳秒与Timestamp计算纳秒标记返回的纳秒之间的差异。

If you run the below program, you'll see the difference between actual nanoseconds and the one returned by Timestamp way of calculating nanosecods.

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 discussion about Timestamp that says it stores time up to nanoseconds , does not seems to be so correct.. Isn't?

推荐答案

以毫秒表示的时间并不代表纳米时间。更精确它根本不可能。您应该使用设置实际纳米。

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));

// ...

这篇关于java.sql.Timestamp存储NanoSeconds的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 19:41