Understanding the nuances of kk:mm, HH:mm, and hh:mm in SimpleDateFormat
When utilizing Java's SimpleDateFormat for manipulating date and time, it's crucial to discern the subtle differences between the "kk:mm," "HH:mm," and "hh:mm" format specifiers. Let's delve into each of these formats:
This format represents time in a 24-hour format, with hour values ranging from 01 to 24. For instance, 01:00 represents 1:00 AM, while 24:00 represents midnight.
Similar to "kk:mm," "HH:mm" represents time in a 24-hour format. However, the allowable hour values range from 00 to 23, meaning that there is no "24:00" representation. Instead, midnight is represented as 00:00.
This format employs a 12-hour clock with an AM/PM indicator. Hour values range from 01 to 12, where 01 represents 1:00 AM and 12 represents 12:00 PM.
Example
To illustrate these differences, consider the following code snippet:
SimpleDateFormat broken = new SimpleDateFormat("kk:mm:ss"); SimpleDateFormat working = new SimpleDateFormat("HH:mm:ss"); SimpleDateFormat working2 = new SimpleDateFormat("hh:mm:ss"); broken.setTimeZone(TimeZone.getTimeZone("Etc/UTC")); working.setTimeZone(TimeZone.getTimeZone("Etc/UTC")); System.out.println(broken.format(epoch)); System.out.println(working.format(epoch)); System.out.println(working2.format(epoch));
Output:
24:00:00 00:00:00 05:30:00
As you can observe, "kk:mm" returns the time in a 24-hour format with a value of 24:00:00. "HH:mm" correctly formats the time as 00:00:00 because there is no 24:00 representation in a 24-hour clock. However, "hh:mm" produces an unexpected result of 05:30:00. This is because the "hh:mm" format specifies a 12-hour clock, and since the correct time is 00:00 UTC, the equivalent 12-hour representation is 12:00 AM. However, the code does not set the time zone for "working2," which results in the use of the default system time zone. In this case, the system time zone may not align with UTC, leading to an incorrect result.
The above is the detailed content of What is the difference between 'kk:mm', 'HH:mm', and 'hh:mm' in Java's SimpleDateFormat?. For more information, please follow other related articles on the PHP Chinese website!