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?
Asked
Active
Viewed 705 times
9 Answers
1
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
- 39,360
- 16
- 67
- 93
1
The Calendar
interface has some nice methods, including before
, after
, and equals
.

rynmrtn
- 3,371
- 5
- 28
- 44
-
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 Dec 07 '09 at 18:44
0
Date date1 = // whatever
Date date2 = // whatever
Long fiveDaysInMilliseconds = 1000 * 60 * 60 * 24 * 5
boolean moreThan5Days = Math.abs(date1.getTime() - date2.getTime()) > fiveDaysInMilliseconds

Dónal
- 185,044
- 174
- 569
- 824
-
2
-
Thanks, I forgot the calls to 'getTime()' - I've been working with Groovy recently which overloads the '-' operator so you can say `date1 - date2` – Dónal Dec 07 '09 at 19:54
0
You can do
Long DAY_IN_MILLIS = 86400000;
if((dateA - dateB) > DAY_IN_MILLIS * 5) {
// dateA is more than 5 days older than dateB
}

Dónal
- 185,044
- 174
- 569
- 824

MattGrommes
- 11,974
- 9
- 37
- 40
0
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());
}

user85421
- 28,957
- 10
- 64
- 87
-1
days = (date2.getTime() - date1.getTime())/86400000L

Reverend Gonzo
- 39,701
- 6
- 59
- 77
-
2This is maybe the most efficient, but this does not take DST into account. – BalusC Dec 07 '09 at 18:21
-
1
-1
days = (date2.getTime() - date1.getTime())

user226593
- 27
- 2
-
1This is not correct since java.util.Date.getTime() returns number of milliseconds. So this difference gives number of milliseconds between date1 and date2. – wheleph Dec 07 '09 at 19:37