Java Calendar problem: why are these two Dates not equal?
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?
Truncate the Milliseconds field
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.
use JodaTime instead, its so much better (than the standard Date and Calendar) for manipulating dates and time.
You need to clear milleseconds
After
Calendar c1=Calendar.getInstance();
add
c1.clear();
That's a bit easier to type than c1.clear(Calendar.MILLISECOND);
Works a treat.
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;
}
精彩评论