import java.io.*;
public class testing {
public static void main(String a[]) throws Exception{
Date d1=new Date();
Thread.sleep(2000);
Date d2=new Date();
if(d1.equals(d2)){
System.out.println("Both equal");
}else{
System.out.println("Both not equal");
}
Calendar c1=Calendar.getInstance();
Calendar c2=Calendar.getInstance();
c1.setTime(d1);
c2.setTime(d2);
c1.clear(Calendar.HOUR);
c1.clear(Calendar.MINUTE);
c1.clear(Calendar.SECOND);
c2.clear(Calendar.HOUR);
c2.clear(Calendar.MINUTE);
c2.clear(Calendar.SECOND);
if(c2.compareTo(c1) == 0){
System.out.println("Cal Equal");
}else {
System.out.println("Cal Not Equal");
}
}
}
When I run the above code multiple times of which each time (for printing if conditions of date) 'Both not equal' is printed but (for if condition of Calendar) sometimes it prints 'Cal Equal' and sometimes 'Cal Not Equal'. Can anyone please explain me why this is so?
The main reason I was trying this because I want to compare two dates. Both have same day, month and Year but different time of the day when the objects were created. I want them to be compared equal(same). How should I do this?
There are two ways to check if two dates are equal in Java : Date's equals() method - return true if two dates are equal. Date's compareTo() method - return zero if two dates are equal.
In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.
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.
What is difference between Java Date and Calendar classes? The difference between Date and Calendar is that Date class operates with specific instant in time and Calendar operates with difference between two dates.
Calendars have milliseconds, too. Add this:
c1.clear(Calendar.MILLISECOND);
c2.clear(Calendar.MILLISECOND);
But it's easier to achieve that functionality using DateUtils.truncate() from Apache Commons / Lang
c1 = DateUtils.truncate(c1, Calendar.DATE);
c2 = DateUtils.truncate(c2, Calendar.DATE);
This removes all hours, minutes, seconds and milliseconds.
I believe Calendar also has Millisecond precision. If you want to continue your code, add
c1.clear(Calendar.MILLISECOND);
c2.clear(Calendar.MILLISECOND);
then try your comparison.
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