Hour Format Specifiers in SimpleDateFormat
When employing SimpleDateFormat to format time values, it's crucial to understand the differences among the hour format specifiers kk:mm, HH:mm, and hh:mm.
kk:mm
The kk specifier represents hours on a 24-hour scale, ranging from 01 to 24. For instance, 24:00:00 indicates midnight.
HH:mm
Unlike kk, HH specifies hours on a 24-hour scale from 00 to 23. 00:00:00 denotes midnight.
hh:mm
The hh specifier displays hours on a 12-hour scale, using 01 to 12 in conjunction with AM/PM. Therefore, 12:00:00 AM or 12:00:00 PM would represent midday.
Consider the following Java code:
SimpleDateFormat broken = new SimpleDateFormat("kk:mm:ss"); broken.setTimeZone(TimeZone.getTimeZone("Etc/UTC")); SimpleDateFormat working = new SimpleDateFormat("HH:mm:ss"); working.setTimeZone(TimeZone.getTimeZone("Etc/UTC")); SimpleDateFormat working2 = new SimpleDateFormat("hh:mm:ss"); working.setTimeZone(TimeZone.getTimeZone("Etc/UTC")); System.out.println(broken.format(epoch)); System.out.println(working.format(epoch)); System.out.println(working2.format(epoch));
This code prints the following output:
24:00:00 00:00:00 05:30:00
The discrepancy in working2's output is because the code sets working2's timezone but not its format. As a result, it wrongly displays 05:30:00 AM or PM, whereas it should output 12:00:00 AM.
The above is the detailed content of What is the difference between 'kk:mm', 'HH:mm', and 'hh:mm' in SimpleDateFormat?. For more information, please follow other related articles on the PHP Chinese website!