Java Calendar problem: why are these two Dates not equal?

Viewed 15371
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?

6 Answers

Reset time using the below method before compare dates

private Calendar resetHours(Calendar cal) {
        cal.set(Calendar.HOUR, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND,0);
        cal.set(Calendar.HOUR_OF_DAY,0);
        cal.set(Calendar.MILLISECOND,0);
        return cal;
    }
Related