Date: 2011oct28
Language: Java
Keywords: GregorianCalendar
Q. Java: get the 12-hour time when I am using Calendar? (Eg 1pm for 13:00)
A. Calendar has HOUR (which seems to be a 12-hour time)
and HOUR_OF_DAY (which is the 24-hour time).
But HOUR gives an unexpected result from noon to 1pm
and midnight to 1am. It is 0 instead of 12.
int hourWrong = mycal.get(Calendar.HOUR); // WRONG
So I prefer to use HOUR_OF_DAY and convert it myself:
int get12Hour(Calendar cal) {
int hour = cal.get(Calendar.HOUR_OF_DAY);
if (hour == 0) hour = 12; // at 30 minutes into the day we want 12:30 not 00:30
if (hour > 12) hour -= 12;
return hour;
}