Home > Java > javaTutorial > What is the difference between 'kk:mm', 'HH:mm', and 'hh:mm' in SimpleDateFormat?

What is the difference between 'kk:mm', 'HH:mm', and 'hh:mm' in SimpleDateFormat?

Barbara Streisand
Release: 2024-11-19 04:35:02
Original
511 people have browsed it

What is the difference between

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));
Copy after login

This code prints the following output:

24:00:00
00:00:00
05:30:00
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template