Compare only the time portion of two dates, ignoring the date part

前端 未结 8 817
谎友^
谎友^ 2021-01-07 16:34

What\'s a good method to, given two Date objects, compare the difference between their time portion only, completely ignoring Year, Month and Day?

It\'s quite the op

8条回答
  •  一整个雨季
    2021-01-07 16:59

    If you want to compare the underlying binary (long int) values of the dates, you can do this:

    public int compareTimes(Date d1, Date d2)
    {
        int     t1;
        int     t2;
    
        t1 = (int) (d1.getTime() % (24*60*60*1000L));
        t2 = (int) (d2.getTime() % (24*60*60*1000L));
        return (t1 - t2);
    }
    

    Addendum 1

    This technique has the advantage of speed, because it uses the underlying long value of the Date objects directly, instead of converting between ticks and calendar components (which is rather expensive and slow). It's also a lot simpler than messing with Calendar objects.

    Addendum 2

    The code above returns the time difference as an int, which will be correct for any pair of times, since it ignores the year/month/day portions of the dates entirely, and the difference between any two times is no more than 86,400,000 ms (= 1000 ms/sec × 60 sec/min × 60 min/hr × 24 hr/day).

提交回复
热议问题