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?
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
LocalDatetype 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.)