Best way to compare Time in Java

17,012

Solution 1

Date.getTime() is not deprecated and gives you a long representing milliseconds since the epoch. You can use this as basis for such simple comparisons.

long diffInMins = Math.abs(date1.getTime() - date2.getTime()) / 60000;

Solution 2

Consider using the JodaTime library which makes this kind of thing much easier. This will eventually be part of the official jdk. (crosses fingers)

Solution 3

As Mechkov says, you can create a Calendar and use the before, after and compare methods to test the difference.

If what you want is to get the minutes of the calendar, you simply have to use this

Calendar cal = Calendar.getInstance();
int minutes = cal.get(Calendar.MINUTE);

Hope it helps!

Share:
17,012

Related videos on Youtube

auwall12688
Author by

auwall12688

Updated on June 04, 2022

Comments

  • auwall12688
    auwall12688 almost 2 years

    I need to compare two times in java and make sure they are within ten minutes from each other. This would seem simple enough and was simple enough before Date was deprecated. Does anyone have any idea of how the best way to program this in java is? I saw the gregorian calendar but i dont see how to access the fields for minutes or day etc.

    • Bruno
      Bruno over 12 years
      java.util.Date isn't deprecated as far as I know (many of its methods are).
    • James Oravec
      James Oravec almost 10 years
      You have Date, Calendar, and several options from 3rd parties. Depending on your use, you may need to account for daylight savings time, and others you may need to try to avoid it. You can look at: stackoverflow.com/questions/23914997/… to see some good examples that use milliseconds from 1970 and some other options too.
  • Johan Sjöberg
    Johan Sjöberg over 12 years
    will, or is rumored to be part of the jdk? There is a difference..