在Java中,我如何将HHMM格式的时间格式化为HH:MM AM/PM。

huangapple go评论61阅读模式
英文:

In Java how can I format a Time of HHMM to HH:MM AM/PM

问题

我有一个以 HHMM 格式表示的时间(1643),我希望将它格式化为 HH:MM AM/PM(04:43 PM)。

在Java中,我该如何实现这个?

对于日期,我正在做类似的操作,将格式为 YYYMMDD(20201013)的日期格式化为 MM/DD/YYY(10/13/2020),使用以下代码:

new java.text.SimpleDateFormat("yyyyMMdd").parse($F{date})
英文:

I have a time in the format HHMM (1643) and I want it to be formatted to HH:MM AM/PM (04:43 PM)

How can I achieve this in Java?

I'm doing something similar for the date which is formatted YYYMMDD (20201013) into MM/DD/YYY (10/13/2020) with this code:

new java.text.SimpleDateFormat("yyyyMMdd").parse($F{date})

答案1

得分: 4

你可以使用DateTimeFormatterLocalTime来自java.time

首先,使用DateTimeFormatter将时间解析为LocalTime。然后再按照您的期望格式将LocalTime格式化为字符串。

LocalTime time = LocalTime.parse("1643", DateTimeFormatter.ofPattern("HHmm"));
String formattedTime = time.format(DateTimeFormatter.ofPattern("hh:mm a"));
System.err.println(formattedTime);

输出:04:43 PM

英文:

You can use DateTimeFormatter & LocalTime from java.time

First, parse the time as LocalTime using DateTimeFormatter. Then again format the LocalTime into String in your desire format.

LocalTime time = LocalTime.parse("1643", DateTimeFormatter.ofPattern("HHmm"));
String formattedTime = time.format(DateTimeFormatter.ofPattern("hh:mm a"));
System.err.println(formattedTime);

Output: 04:43 PM

huangapple
  • 本文由 发表于 2020年10月15日 02:20:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/64359326.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定