1

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?

9 Answers9

12

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

Joel
  • 29,538
  • 35
  • 110
  • 138
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
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
-1

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

user226593
  • 27
  • 2
  • 1
    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 Dec 07 '09 at 19:37