Tuesday, May 24, 2005

The Calendar Quiz

Given the code snippet below, what would you expect the hour variable is set to?
Calendar calendar = Calendar.getInstance();
calendar.clear(Calendar.HOUR_OF_DAY);
calendar.clear(Calendar.MINUTE);
calendar.clear(Calendar.SECOND);
calendar.clear(Calendar.MILLISECOND);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
Select an answer:
  1. 0
  2. null
  3. it depends
The right answer is the last one. The clear(int field) method does not change the value of the calendar's hour field. The documentation says: The HOUR_OF_DAY, HOUR and AM_PM fields are handled independently and the the resolution rule for the time of day is applied. Clearing one of the fields doesn't reset the hour of day value of this Calendar. Use set(Calendar.HOUR_OF_DAY, 0) to reset the hour value..

If only I knew it before :-)

0 Comments:

Post a Comment

<< Home