What's the efficient way of finding say if a date is 5 days earlier than another day? Do I need to parse both days using a particular SimpleDateFormat first before I compare?
This is maybe the most efficient, but this does not take DST into account.
BalusC
2009-12-07 18:21:10
-1 That's wrong unless the Date instances were derived from UTC times.
sleske
2010-08-30 13:27:21
+1
A:
Most quickly, but least accurately, you might just put both into a java.util.Date, getTime() on both, and divide the difference by the number of milliseconds in a day.
You could make it a bit more accurate by creating two Calendar objects, and work with those.
If you really want to solve this well, and have a good bit of time on your hands, look at Joda Time.
Dean J
2009-12-07 18:07:09
+1
A:
The Calendar
interface has some nice methods, including before
, after
, and equals
.
rynmrtn
2009-12-07 18:08:51
The whole API is however fairly epic fail: http://stackoverflow.com/questions/1697215/what-is-your-favourite-java-api-annoyance/1697229#1697229 See for example the calendar example and the jodatime example in this topic: http://stackoverflow.com/questions/567659/calculate-elapsed-time-in-java-groovy/1776721#1776721
BalusC
2009-12-07 18:44:56
A:
Date date1 = // whatever
Date date2 = // whatever
Long fiveDaysInMilliseconds = 1000 * 60 * 60 * 24 * 5
boolean moreThan5Days = Math.abs(date1.getTime() - date2.getTime()) > fiveDaysInMilliseconds
Don
2009-12-07 18:16:11
Thanks, I forgot the calls to 'getTime()' - I've been working with Groovy recently which overloads the '-' operator so you can say `date1 - date2`
Don
2009-12-07 19:54:03
A:
You can do
Long DAY_IN_MILLIS = 86400000;
if((dateA - dateB) > DAY_IN_MILLIS * 5) {
// dateA is more than 5 days older than dateB
}
MattGrommes
2009-12-07 18:19:27
This is not correct since java.util.Date.getTime() returns number of milliseconds. So this difference gives number of milliseconds between date1 and date2.
wheleph
2009-12-07 19:37:59
A:
If you need to ignore the time of the dates, you can do something like
public static boolean compare5days(Date date, Date another) {
Calendar cal = Calendar.getInstance();
cal.setTime(another);
cal.add(Calendar.DATE, -5);
// clear time
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return date.before(cal.getTime());
}
Carlos Heuberger
2009-12-07 20:19:27