Best way to compare Time in Java
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!
Related videos on Youtube
auwall12688
Updated on June 04, 2022Comments
-
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 over 12 years
java.util.Date
isn't deprecated as far as I know (many of its methods are). -
James Oravec almost 10 yearsYou 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 over 12 yearswill, or is rumored to be part of the jdk? There is a difference..