• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Devaka Cooray
  • Knute Snortum
  • Paul Clapham
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Frits Walraven
  • Ganesh Patekar
  • Tim Holloway
  • salvin francis

Problems with Calendar.clear() method  RSS feed

Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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().
Bring me the box labeled "thinking cap" ... and then read this tiny ad:
how do I do my own kindle-like thing - without amazon
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!