2

I am trying to clear the HOUR_OF_DAY from the Calendar in Java. For every other field, the value is getting cleared. Only for HOUR_OF_DAY it is not.

Calendar c = Calendar.getInstance();
c.clear(Calendar.MINUTE);
c.clear(Calendar.HOUR_OF_DAY);
System.out.println(c.getTime());

prints Wed May 04 12:00:31 IST 2016

at 2 PM it prints Wed May 04 14:00:31 IST 2016

ffff
  • 2,853
  • 1
  • 25
  • 44
  • I dont feel like duplicating the question since there it does not specify the API doc (the reason behind why it doesnt work) @piyushjaiswal – ffff May 04 '16 at 07:06
  • For a date-only value, without time-of-day, use [`java.time.LocalDate`](https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html). – Basil Bourque Apr 26 '17 at 05:00

1 Answers1

6

From API of clear:

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.

So,

c.set(Calendar.HOUR_OF_DAY, 0);

should get what you want.

dejvuth
  • 6,986
  • 3
  • 33
  • 36
  • clear() should throw a RuntimeException if the the api is used incorrectly, no? This is a real gotcha. – JohnyTex Dec 15 '16 at 09:46