Comparing two Calendar objects

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

It will fail if the two calendars are in different time zones - they could represent the exact same millisecond, but that instant could fall into different days based on the time zone.

It will also arguably fail if the two calendars represent different calendar systems - even if they represent the same "day", if the two calendars would represent that day differently, you could argue that it should fail.

Personally, I would strongly advise you to use Joda Time which has a LocalDate type to represent just a date - that would get rid of the time zone issue, but not the calendar system issue. If you can always assume that you're using the same calendar system, then that's okay.

(Additionally, performing string operations just for comparison purposes is ugly - I'd just check calendar.get(Calendar.YEAR) etc directly.)


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.


You can use somehing like DateUtils

public boolean isSameDay(Calendar cal1, Calendar cal2) {
    if (cal1 == null || cal2 == null)
        return false;
    return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA)
            && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) 
            && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR));
}

You can also check if is the same date-time:

public boolean isSameDateTime(Calendar cal1, Calendar cal2) {
    // compare if is the same ERA, YEAR, DAY, HOUR, MINUTE and SECOND
    return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA)
           && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)
           && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR)
           && cal1.get(Calendar.HOUR_OF_DAY) == cal2.get(Calendar.HOUR_OF_DAY)
           && cal1.get(Calendar.MINUTE) == cal2.get(Calendar.MINUTE)
           && cal1.get(Calendar.SECOND) == cal2.get(Calendar.SECOND));
}