Date: 2011oct28
Update: 2025sep17
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.
Here is a full example:
import java.util.Calendar;
import java.util.GregorianCalendar;
class Demo {
// I prefer to use HOUR_OF_DAY and convert it myself
static 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;
}
public static void main(String []args) {
final GregorianCalendar mycal = new GregorianCalendar();
// We can not use Calendar.HOUR (12-hour time) because it gives
// hour=0 for noon
final int hourWrong = mycal.get(Calendar.HOUR); // WRONG
System.out.println("sometimes wrong 12 hour=" + hourWrong);
// So I prefer to use my own function
final int hourGood = get12Hour(mycal);
System.out.println("correct 12 hour=" + hourGood);
}
}
Output (at 12:05 in the afternoon):
sometimes wrong 12 hour=0
correct 12 hour=12