4

I'm trying to do a simple date comparison between yesterday and today

if (yesterday.before(today)) {
 ...
}

The issue is that with the before method I will eval to true even if it's just a few seconds difference. How might I compare just the day (because I only want to eval this to true if it was the previous day (minutes/seconds should be ignored)

Thank you in advance

Toran Billups
  • 27,111
  • 40
  • 155
  • 268
  • compare between date in java.util.Date or java.util.Calendar – mKorbel Jun 18 '11 at 20:57
  • 3
    I'm surprised there's no easy way to do this using the standard API. If you can't use commons lang for some reason (as per Lobo), I suggest you convert each Date to a number of days since the epoch (i.e. `millisSinceEpoch / MILLIS_IN_DAY`). – OpenSauce Jun 18 '11 at 21:05

4 Answers4

12

using DateUtils -

if (!DateUtils.isSameDay(yesterday, today) && (yesterday.before(today)) {
   //...
}

EDIT: it can be done without DateUtils as well. See this thread.

Community
  • 1
  • 1
Praveen Lobo
  • 6,956
  • 2
  • 28
  • 40
5

If you don't want to use a 3rd party library implement a method like this:

public boolean before(Calendar yesterday, Calendar today) {
    if(yesterday == today) return false;
    if(yesterday == null || today == null) return false;
    return  yesterday.get(Calendar.YEAR) < today.get(Calendar.YEAR) ? true : 
        yesterday.get(Calendar.YEAR) == today.get(Calendar.YEAR) && yesterday.get(Calendar.DAY_OF_YEAR) < today.get(Calendar.DAY_OF_YEAR);
}
s106mo
  • 1,243
  • 2
  • 14
  • 20
4

If you're up to adding a library that handles dates better than the standard Java libraries, you might want to look at Joda.

Using Joda, you can compute difference between days by:

  Days d = Days.daysBetween(startDate, endDate);
  int days = d.getDays();

where startDate and endDate are the Joda version of dates, DateTime (actually a superclass of that).

Converting Java Date objects to Joda DateTime objects can be done by a constructor call:

DateTime dateTime = new DateTime(javaDate);

Adding this library may be overkill for this specific problem, but if you deal with date and time manipulation a lot, the library is definitely worth it.

Don Roby
  • 40,677
  • 6
  • 91
  • 113
3

If you want to stick to Date you could temporarily lower your current date by one day. If before() still leads to the same result you have a timespan of at least one day.

final static long DAY_MILLIS = 86400000;

Date d1 = new Date(2011, 06, 18);
Date d2 = new Date(2011, 06, 16);

Date temp = new Date(d1.getTime() - DAY_MILLIS);

if (temp.before(d2)) 
  // Do stuff
}

Please note I used a deprecated constructor but it should do the job.

pdresselhaus
  • 679
  • 14
  • 32