Comparing two Calendar objects

Charlie-Blake picture Charlie-Blake · Oct 19, 2012 · Viewed 77.9k times · Source

I want to compare two Calendar objects to see if they both contain the same date. I don't care about any value below days.

I've implemented this and I can't think about any case where it should fail:

private static boolean areEqualDays(Calendar c1, Calendar c2) {
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
    return (sdf.format(c1.getTime()).equals(sdf.format(c2.getTime())));
}

Is this approach correct or should I compare c1 and c2 field by field?

Answer

Drogba picture Drogba · Oct 19, 2012

Try compareTo

Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.compareTo(c2);

Returns:

the value 0 if the time represented by the argument is equal to the time represented by this Calendar; a value less than 0 if the time of this Calendar is before the time represented by the argument; and a value greater than 0 if the time of this Calendar is after the time represented by the argument.

EDIT

import org.apache.commons.lang3.time.DateUtils;

You can use DateUtils.isSameDay to check if it's the same day.

boolean isSameDay = DateUtils.isSameDay(c1, c2);

28 Mar 2002 13:45 and 28 Mar 2002 06:01 would return true. 28 Mar 2002 13:45 and 12 Mar 2002 13:45 would return false.