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?
For comparing the two dates, we have used the compareTo() method. If both dates are equal it prints Both dates are equal. If date1 is greater than date2, it prints Date 1 comes after Date 2. If date1 is smaller than date2, it prints Date 1 comes after Date 2.
equals() method compares this GregorianCalendar to the specified Object. The result is true if and only if the argument is a GregorianCalendar object that represents the same time value (millisecond offset from the Epoch) under the same Calendar parameters and Gregorian change date as this object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With