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

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.


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.

Tags:

Java