英文:
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
你可以使用DateTimeFormatter和LocalTime来自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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论