It's not a secret anymore!
The moose likes Java in General and the fly likes Problems with Calendar.clear() method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Problems with Calendar.clear() method" Watch "Problems with Calendar.clear() method" New topic

Problems with Calendar.clear() method

Dar Var
Ranch Hand

Joined: Oct 12, 2004
Posts: 74
Here is an extract of my code.
I convert a Calendar to a Date object and to a Calendar again.
I then try and clear fields to just leave the year part.
For the hour part I use set(Calendar.HOUR_OF_DAY, 0) as described by the JavaDoc.

Input = startDate = Thu Jan 29 23:59:55 GMT 2009

Actual Result = startDate = Thu Jan 29 00:00:00 GMT 2009

The Result I expected is Thu Jan 01 00:00:00 GMT 2009

Why is the Calendar.DATE field cleared?
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
I guess you mean, why isn't the date cleared? The problem is that clear() doesn't do what you think it does. It doesn't really set the value to zero - instead it tells Calendar to act as if that field has never been set. This is relevant if you set some other fields - it determines which fields can change to ensure a logical, consistent date, and which cannot. The problem is that the time information is really still in there, and unless you explicitly set some fields to different values, the Calendar will revert to this original time info. It doesn't really make much sense.

Instead, you need to set() each of those fields to zero. Or to one, in the case of DATE. That will have the desired effect.

Incidentally, you probably should also set the MILLISECOND value to zero. It doesn't get displayed by Date's toString(), but it is part of the data, and will effect things like equals() and compareTo().

"I'm not back." - Bill Harding, Twister
I agree. Here's the link:
subject: Problems with Calendar.clear() method
It's not a secret anymore!