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

前端 未结 5 1125
悲&欢浪女
悲&欢浪女 2020-12-14 19:53

Please include the nanos, otherwise it would be trivial:

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

[EDIT] I want the most precis

5条回答
  •  别那么骄傲
    2020-12-14 20:21

    Building on mmyers code...

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

提交回复
热议问题