gpt4 book ai didi

java - 如何计算两个 Java java.sql.Timestamps 之间的差异?

转载 作者:搜寻专家 更新时间:2023-10-30 21:06:40 25 4
gpt4 key购买 nike

请包括 nanos,否则将是微不足道的:

long diff = Math.abs(t1.getTime () - t2.getTime ());

[编辑] 我想要最精确的结果,所以不要加倍;只有整数/长算术。此外,结果必须是积极的。伪代码:

Timestamp result = abs (t1 - t2);

例子:

t1 = (time=1001, nanos=1000000), t2 = (time=999, nanos=999000000)
-> diff = (time=2, nanos=2000000)

是的,java.sql.Timestamp 中的毫秒在时间和 nanos par 中是重复的,所以 1001 毫秒意味着 1 秒 (1000) 和 1 毫秒,它在 time 部分和 nanos 部分,因为 1 毫秒 = 1000000 纳秒)。这比看起来要狡猾得多。

我建议不要在没有实际测试代码或准备好工作代码示例的情况下发布答案:)

最佳答案

经过一个小时和各种单元测试,我想出了这个解决方案:

public static Timestamp diff (java.util.Date t1, java.util.Date t2)
{
// Make sure the result is always > 0
if (t1.compareTo (t2) < 0)
{
java.util.Date tmp = t1;
t1 = t2;
t2 = tmp;
}

// Timestamps mix milli and nanoseconds in the API, so we have to separate the two
long diffSeconds = (t1.getTime () / 1000) - (t2.getTime () / 1000);
// For normals dates, we have millisecond precision
int nano1 = ((int) t1.getTime () % 1000) * 1000000;
// If the parameter is a Timestamp, we have additional precision in nanoseconds
if (t1 instanceof Timestamp)
nano1 = ((Timestamp)t1).getNanos ();
int nano2 = ((int) t2.getTime () % 1000) * 1000000;
if (t2 instanceof Timestamp)
nano2 = ((Timestamp)t2).getNanos ();

int diffNanos = nano1 - nano2;
if (diffNanos < 0)
{
// Borrow one second
diffSeconds --;
diffNanos += 1000000000;
}

// mix nanos and millis again
Timestamp result = new Timestamp ((diffSeconds * 1000) + (diffNanos / 1000000));
// setNanos() with a value of in the millisecond range doesn't affect the value of the time field
// while milliseconds in the time field will modify nanos! Damn, this API is a *mess*
result.setNanos (diffNanos);
return result;
}

单元测试:

    Timestamp t1 = new Timestamp (0);
Timestamp t3 = new Timestamp (999);
Timestamp t4 = new Timestamp (5001);
// Careful here; internally, Java has set nanos already!
t4.setNanos (t4.getNanos () + 1);

// Show what a mess this API is...
// Yes, the milliseconds show up in *both* fields! Isn't that fun?
assertEquals (999, t3.getTime ());
assertEquals (999000000, t3.getNanos ());
// This looks weird but t4 contains 5 seconds, 1 milli, 1 nano.
// The lone milli is in both results ...
assertEquals (5001, t4.getTime ());
assertEquals (1000001, t4.getNanos ());

diff = DBUtil.diff (t1, t4);
assertEquals (5001, diff.getTime ());
assertEquals (1000001, diff.getNanos ());

diff = DBUtil.diff (t4, t3);
assertEquals (4002, diff.getTime ());
assertEquals (2000001, diff.getNanos ());

关于java - 如何计算两个 Java java.sql.Timestamps 之间的差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/582278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com