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
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
All of the world's problems can be solved in a garden - Geoff Lawton. Tiny ad:
RavenDB is an Open Source NoSQL Database that’s fully transactional (ACID) across your database