什么是kk:mm,HH:mm和hh:mm格式之间的区别?
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));
Run Code Online (Sandbox Code Playgroud)
打印:
24:00:00
00:00:00
05:30:00
Run Code Online (Sandbox Code Playgroud)
kam*_*gin 54
kk:(01-24)看起来像01,02..24.
HH:(00-23)看起来像00,01..23.
hh :(上午01点到下午12点)看起来像01,02..12.
所以最后的printout(working2)有点奇怪.它应该说是12:00:00(编辑:如果你设置的working2时区和格式,(如kdagli所指出)你不是)
小智 16
实际上最后一个并不奇怪.代码正在设置工作时区而不是工作2.
SimpleDateFormat working2 = new SimpleDateFormat("hh:mm:ss");
工作的.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
kk从1到24,HH从0到23,hh从1到12(AM/PM).
修复此错误会给出:
24:00:00
00:00:00
01:00:00
Run Code Online (Sandbox Code Playgroud)
如果这是为了向用户显示一天中的某个时间,那么在 20 个中的至少 19 个中,您不需要\xe2\x80\x99t 需要关心kk,HH也不需要hh需要关心。我建议你使用这样的东西:
DateTimeFormatter defaultTimeFormatter\n = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);\n System.out.format("%s: %s%n",\n Locale.getDefault(), LocalTime.MIN.format(defaultTimeFormatter));\nRun Code Online (Sandbox Code Playgroud)\n\n关键是它在不同的默认区域设置中给出不同的输出。例如:
\n\n\n\n\nRun Code Online (Sandbox Code Playgroud)\nen_SS: 12:00 AM\nfr_BL: 00:00\nps_AF: 0:00\nes_CO: 12:00 a.m.\n
本地化的格式旨在符合不同文化的期望。因此,它们通常会给用户带来更好的体验,并且省去了编写格式模式字符串的麻烦,而格式模式字符串总是容易出错。
\n\n我进一步建议您不要使用\xe2\x80\x99tSimpleDateFormat. 那个类是出了名的麻烦,而且幸运的是早已过时了。相反,我使用 java.time,现代 Java 日期和时间 API。和它一起工作真是太好了。
当然,如果您需要解析具有指定格式的字符串,并且您有非常具体的格式要求,那么使用格式模式字符串是很好的选择。实际上,小时有四种不同的模式字母可供选择(引自文档):
\n\n Symbol Meaning Presentation Examples\n ------ ------- ------------ -------\n h clock-hour-of-am-pm (1-12) number 12\n K hour-of-am-pm (0-11) number 0\n k clock-hour-of-day (1-24) number 24\n H hour-of-day (0-23) number 0\nRun Code Online (Sandbox Code Playgroud)\n\nH并在实践中h得到运用。据我所知k和K不知道(它们可能只是为了完整性而被包括在内)。但让\xe2\x80\x99s 来看看它们全部在运行:
DateTimeFormatter timeFormatter\n = DateTimeFormatter.ofPattern("hh:mm a HH:mm kk:mm KK:mm a", Locale.ENGLISH);\n System.out.println(LocalTime.of(0, 0).format(timeFormatter));\n System.out.println(LocalTime.of(1, 15).format(timeFormatter));\n System.out.println(LocalTime.of(11, 25).format(timeFormatter));\n System.out.println(LocalTime.of(12, 35).format(timeFormatter));\n System.out.println(LocalTime.of(13, 40).format(timeFormatter));\nRun Code Online (Sandbox Code Playgroud)\n\n\n\n\nRun Code Online (Sandbox Code Playgroud)\n12:00 AM 00:00 24:00 00:00 AM\n01:15 AM 01:15 01:15 01:15 AM\n11:25 AM 11:25 11:25 11:25 AM\n12:35 PM 12:35 12:35 00:35 PM\n01:40 PM 13:40 13:40 01:40 PM\n
如果您不需要\xe2\x80\x99 不需要前导零,只需指定一个模式字母,即h代替hh或H代替HH。解析时仍会接受两位数字,如果要打印的数字大于 9,仍会打印两位数字。
DateTimeFormatter。| 归档时间: |
|
| 查看次数: |
95793 次 |
| 最近记录: |