Win a copy of Microservices Testing (Live Project) this week in the Spring forum!
  • 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
  • Liutauras Vilda
  • Henry Wong
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
  • Piet Souris
  • Mikalai Zaikin
  • Himai Minh

Problems with Calendar.clear() method

Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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().
    Bookmark Topic Watch Topic
  • New Topic