Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two Calendar objects

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?

like image 656
Charlie-Blake Avatar asked Oct 19 '12 08:10

Charlie-Blake


People also ask

How can I compare two dates?

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.

How does Gregorian calendar compare to date in Java?

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.


1 Answers

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.

like image 162
Drogba Avatar answered Sep 22 '22 02:09

Drogba