Home > Java > javaTutorial > What are the differences between HH:mm, hh:mm, and kk:mm in Java's SimpleDateFormat?

What are the differences between HH:mm, hh:mm, and kk:mm in Java's SimpleDateFormat?

Patricia Arquette
Release: 2024-11-17 17:03:01
Original
521 people have browsed it

What are the differences between HH:mm, hh:mm, and kk:mm in Java's SimpleDateFormat?

Distinguishing between java Formatting Patterns: HH:mm, hh:mm, and kk:mm

The SimpleDateFormat class in Java provides various format patterns to display dates and times. While the HH:mm, hh:mm, and kk:mm patterns may seem similar, there are notable differences in their representations.

Consider the following Java code snippet:

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

The output of the provided code is:

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

Let's break down the differences between these patterns:

  • kk:mm: Represents hours (01-24) in a 24-hour format. The output "24:00:00" indicates midnight in this format.
  • HH:mm: Represents hours (00-23) in a 24-hour format. The output "00:00:00" denotes 12:00 AM in this pattern.
  • hh:mm: Represents hours (01-12) using a 12-hour format with AM/PM designations. However, it's important to note that the code example does not set the format to "hh:mm:ss". Instead, it uses the same format as "working", which is "HH:mm:ss". As a result, the output "05:30:00" is incorrect and should have been "12:00:00" in a 12-hour AM/PM format.

Therefore, understanding the nuances of these formatting patterns is crucial for accurately representing dates and times in Java.

The above is the detailed content of What are the differences between HH:mm, hh:mm, and kk:mm in Java's 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