Reputation: 8923
I am using the Calendar object as follows:
Calendar calendar = new GregorianCalendar();
calendar.set(Calendar.HOUR_OF_DAY, 24);
calendar.get(Calendar.HOUR_OF_DAY)
I want the result of this to be 24, as opposed to 0. Is this possible?
Upvotes: 1
Views: 276
Reputation: 44071
First of all, the time 24:00 is a valid time according to ISO-8601 and means midnight start at the next day.
java.util.GregorianCalendar
does not support the hour 24. Please feel free to study following example code with my comments:
// By default lenient behaviour with overflow of 24:00 to next day
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
GregorianCalendar gcal = new GregorianCalendar(2014, Calendar.AUGUST, 17, 0, 0, 0);
gcal.set(Calendar.HOUR_OF_DAY, 24);
System.out.println("HOUR_OF_DAY: " + gcal.get(Calendar.HOUR_OF_DAY)); // 0
System.out.println(sdf.format(gcal.getTime())); // 2014-08-14 00:00
// now switch to strict mode
gcal.setLenient(false);
gcal.set(Calendar.HOUR_OF_DAY, 24);
gcal.getTime(); // triggers recomputation which will fail with following abort
// abort relates to set()-method => java.lang.IllegalArgumentException: HOUR_OF_DAY
Most other libraries do not support setting the time to 24:00, too. Neither Java-8-time nor its predecessor Joda-Time give support. However, Java-8-time can parse such times but never set.
My library Time4J partially allows setting this time, namely for the type PlainTime which indeed has an extended value range from 00:00 until 24:00 (inclusive). However, I have decided to handle it differently for the type PlainTimestamp
(combination of calendar date and wall time) because I want to preserve a bijective unique mapping between timestamp and a single incrementing counter (otherwise the values 2014-08-17 24:00 and 2014-08-18 00:00 would stand for the same timestamp counter causing problems in sorting). The Time4J-solution for this problem is here automatic normalization (with overflow similar to lenient behaviour in the class GregorianCalendar
).
Upvotes: 2
Reputation: 7
I think the command
Calendar.get(Calendar.HOUR_OF_DAY); does the conversion from am/pm to 24H so you don't need to add anything else.
Upvotes: 0
Reputation: 17
If you set the field Calendar.HOUR_OF_DAY to be 24, then it is set to 0 of the next day. the 24th hour of a day does not exist.
Upvotes: 2