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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/582278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 16:31:04  来源:igfitidea点击:

How to calculate the difference between two Java java.sql.Timestamps?

javatimestamp

提问by Aaron Digulla

Please include the nanos, otherwise it would be trivial:

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

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

[EDIT] I want the most precise result, so no doubles; only integer/long arithmetic. Also, the result must be positive. Pseudo code:

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

Timestamp result = abs (t1 - t2);

Examples:

例子:

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

Yes, milliseconds in java.sql.Timestamp are duplicated in the time and the nanos par, so 1001 milliseconds means 1 second (1000) and 1 milli which is in the timepart and the nanospart because 1 millisecond = 1000000 nanoseconds). This is much more devious than it looks.

是的,在java.sql.Timestamp中毫秒被复制的时间和毫微秒不相上下,所以1001个毫秒装置1秒(1000)和1毫这是在time部件和nanos部分,因为1毫秒= 1000000毫微秒)。这比看起来要狡猾得多。

I suggest not to post an answer without actually testing the code or having a working code sample ready :)

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

采纳答案by Aaron Digulla

After one hour and various unit tests, I came up with this solution:

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

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

Unit tests:

单元测试:

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

回答by Steve B.

In what units? your diff above will give milliseconds, Timestamp.nanos() returns an int, which would be in (millionths?) of a millisecond.So do you mean e.g.

在什么单位?你上面的差异将给出毫秒,Timestamp.nanos() 返回一个整数,这将是(百万分之一?)一毫秒。所以你的意思是例如

(t1.getTime () + (.000001*t1.getNanos()) - (t2.getTime () + (.000001*t2.getNanos())

or am I missing something? Another question is do you need this level of precision? AFAIK the JVM isn't guaranteed to be precise at this level, I don't think it'd matter unless you're sure your datasource is that precise.

或者我错过了什么?另一个问题是您需要这种精度水平吗?AFAIK JVM 不能保证在这个级别上是精确的,除非您确定您的数据源是那么精确,否则我认为这无关紧要。

回答by Michael Myers

(old code removed to shorten answer)

(删除旧代码以缩短答案)

EDIT 2:New code:

编辑 2:新代码:

public class ArraySizeTest {
    public static void main(String[] args) throws InterruptedException {
        Timestamp t1 = new Timestamp(System.currentTimeMillis());
        t1.setNanos(t1.getNanos() + 60);
        Thread.sleep(20);
        Timestamp t2 = new Timestamp(System.currentTimeMillis());
        t2.setNanos(t2.getNanos() + 30);
        System.out.println(t1);
        System.out.println(t2);
        // The actual diff...
        long firstTime = (getTimeNoMillis(t1) * 1000000) + t1.getNanos();
        long secondTime = (getTimeNoMillis(t2) * 1000000) + t2.getNanos();
        long diff = Math.abs(firstTime - secondTime); // diff is in nanos
        System.out.println(diff);
        System.out.println(Math.abs(t1.getTime() - t2.getTime()));
    }
    private static long getTimeNoMillis(Timestamp t) {
        return t.getTime() - (t.getNanos()/1000000);
    }
}

Output:

输出:

2009-02-24 10:35:15.56500006
2009-02-24 10:35:15.59600003
30999970
31

Edit 3:If you'd prefer something that returns a Timestamp, use this:

编辑 3:如果您更喜欢返回时间戳的内容,请使用:

public static Timestamp diff(Timestamp t1, Timestamp t2) {
    long firstTime = (getTimeNoMillis(t1) * 1000000) + t1.getNanos();
    long secondTime = (getTimeNoMillis(t2) * 1000000) + t2.getNanos();
    long diff = Math.abs(firstTime - secondTime); // diff is in nanoseconds
    Timestamp ret = new Timestamp(diff / 1000000);
    ret.setNanos((int) (diff % 1000000000));
    return ret;
}
private static long getTimeNoMillis(Timestamp t) {
    return t.getTime() - (t.getNanos()/1000000);
}

This code passes your unit tests.

此代码通过了您的单元测试。

回答by TofuBeer

Building on mmyers code...

基于 mmyers 代码构建...

import java.math.BigInteger;
import java.sql.Timestamp;


public class Main
{
    // 1s == 1000ms == 1,000,000us == 1,000,000,000ns (1 billion ns)
    public final static BigInteger ONE_BILLION = new BigInteger ("1000000000");
    public static void main(String[] args) throws InterruptedException 
    {
        final Timestamp t1;
        final Timestamp t2;
        final BigInteger firstTime;
        final BigInteger secondTime;
        final BigInteger diffTime;

        t1 = new Timestamp(System.currentTimeMillis());
        Thread.sleep(20);
        t2 = new Timestamp(System.currentTimeMillis());

        System.out.println(t1);
        System.out.println(t2);
        firstTime  = BigInteger.valueOf(t1.getTime() / 1000 * 1000).multiply(ONE_BILLION ).add(BigInteger.valueOf(t1.getNanos()));
        secondTime = BigInteger.valueOf(t2.getTime() / 1000 * 1000).multiply(ONE_BILLION ).add(BigInteger.valueOf(t2.getNanos()));
        diffTime   = firstTime.subtract(secondTime);
        System.out.println(firstTime);
        System.out.println(secondTime);
        System.out.println(diffTime);
    }
}

回答by AechoLiu

I use this method to get difference between 2 java.sql.Timestmap

我使用这种方法来获得 2 之间的差异 java.sql.Timestmap

/**
 * Get a diff between two timestamps.
 *
 * @param oldTs The older timestamp
 * @param newTs The newer timestamp
 * @param timeUnit The unit in which you want the diff
 * @return The diff value, in the provided time unit.
 */
public static long getDateDiff(Timestamp oldTs, Timestamp newTs, TimeUnit timeUnit) {
    long diffInMS = newTs.getTime() - oldTs.getTime();
    return timeUnit.convert(diffInMS, TimeUnit.MILLISECONDS);
}

// Examples:
// long diffMinutes = getDateDiff(oldTs, newTs, TimeUnit.MINUTES);
// long diffHours = getDateDiff(oldTs, newTs, TimeUnit.HOURS);