tags:

views:

187

answers:

9

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?

A: 
days = (date2.getTime() - date1.getTime())/86400000L
Milan Ramaiya
This is maybe the most efficient, but this does not take DST into account.
BalusC
-1 That's wrong unless the Date instances were derived from UTC times.
sleske
+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
+11  A: 

The best Java date time API is Joda Time. It makes these tasks, and others, much easier than using the standard API.

Joel
+1  A: 

The Calendar interface has some nice methods, including before, after, and equals.

rynmrtn
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
A: 
Date date1 = // whatever
Date date2 = // whatever

Long fiveDaysInMilliseconds = 1000 * 60 * 60 * 24 * 5    
boolean moreThan5Days = Math.abs(date1.getTime() - date2.getTime()) > fiveDaysInMilliseconds
Don
You can't just say `date1 - date2`.
Michael Myers
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
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
A: 

days = (date2.getTime() - date1.getTime())

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
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