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

前端 未结 8 867
谎友^
谎友^ 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条回答
  •  梦毁少年i
    2021-01-07 17:12

    if you just want to compare the time part of the dates then this would give you the right result -

    public long compareTimes(Date d1, Date d2)
        {
            long     t1;
            long     t2;
            t1 = d1.getHours()*60*60+d1.getMinutes()*60+d1.getSeconds();
            t2 = d2.getHours()*60*60+d2.getMinutes()*60+d2.getSeconds();
            long diff = t1-t2;
            System.out.println("t1 - "+t1+", t2 - "+t2+",  diff - "+diff);
    
            return diff;
        }
    

提交回复
热议问题