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

前端 未结 5 1127
悲&欢浪女
悲&欢浪女 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:18

    I use this method to get difference between 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);
    

提交回复
热议问题