java.sql.Timestamp 的构造函数是这样的:
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 个零)......似乎不是最佳的。
更好的方法可能是时间戳构造函数,它接受以纳秒为单位的时间,然后从中计算出纳秒值。
如果运行以下程序,您将看到实际纳秒与计算纳秒的时间戳方法返回的纳秒之间的差异。
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;
}
所以所有关于 Timestamp 的讨论都说它存储的时间高达纳秒,似乎并不那么正确。不是吗?
最佳答案
以毫秒为单位的时间不代表以纳秒为单位的时间。更准确地说,它根本不可能。你应该使用 Timestamp#setNanos()
设置真正的纳米。
long timeInMillis = System.currentTimeMillis();
long timeInNanos = System.nanoTime();
Timestamp timestamp = new Timestamp(timeInMillis);
timestamp.setNanos((int) (timeInNanos % 1000000000));
// ...
关于java.sql.Timestamp 存储 NanoSeconds 的方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5839411/