[英]LocalTime parsing with AM/PM
I have a time string coming from another source in format "hh:mma", for example, 10:00a or 07:30p. 我有一个来自其他来源的时间字符串,格式为“ hh:mma”,例如10:00a或07:30p。 I need to create an instance of LocalTime
from that string. 我需要从该字符串创建LocalTime
的实例。 I've tried to parse it by calling the method: LocalTime.parse("10:00p", DateTimeFormatter.ofPattern("hh:mma"))
, but it throws an DateTimeParseException
. 我试图通过调用以下方法来解析它: LocalTime.parse("10:00p", DateTimeFormatter.ofPattern("hh:mma"))
,但是它引发了DateTimeParseException
。 In accordance with DateTimeFormatter API , part of the time should be in uppercase and consist of 2 letters (PM instead of p). 根据DateTimeFormatter API的规定 ,部分时间应使用大写字母,并由2个字母(PM代替p)组成。 But is there any method to parse time without changing the sourse line? 但是,有什么方法可以解析时间而不改变路线?
Replace p
with PM
, a
with AM
, then parse it with pattern hh:mm a
. 将p
替换为PM
,将a
替换为AM
,然后使用模式hh:mm a
解析它。
String time = "10:00p";
time = time.replace("p", "PM").replace("a", "AM"); // 10:00PM
LocalTime localTime = LocalTime.parse(time, DateTimeFormatter.ofPattern("hh:mm a", Locale.US));
System.out.println(localTime); // 22:00
But is there any method to parse time without changing the sourse line? 但是,有什么方法可以解析时间而不改变路线?
Yes, this formatter can do that for you: 是的,此格式化程序可以为您做到这一点:
Map<Long, String> ampmStrings = Map.of(0L, "a", 1L, "p");
DateTimeFormatter timeFormatter = new DateTimeFormatterBuilder()
.appendPattern("hh:mm")
.appendText(ChronoField.AMPM_OF_DAY, ampmStrings)
.toFormatter();
With DateTimeFormatterBuilder.appendText
we can define our own texts for both formatting and parsing. 使用DateTimeFormatterBuilder.appendText
我们可以定义自己的文本以进行格式设置和解析。 I used the Java 9+ Map.of
to initialize a map of two key-value pairs. 我使用Java 9+ Map.of
初始化了两个键值对的映射。 If you are using Java 6, 7 or 8, I trust you to initialize the map differently. 如果您使用的是Java 6、7或8,我相信您可以用不同的方式初始化地图。 The rest should still work. 其余的应该仍然有效。
Let's try it out: 让我们尝试一下:
String sourceLine = "10:00a";
LocalTime time = LocalTime.parse(sourceLine, timeFormatter);
System.out.println("Parsed time: " + time);
Output is: 输出为:
Parsed time: 10:00 解析时间:10:00
A yet better option would be if you could persuade your source to provide strings in ISO 8601 format (like 10:00
and 19:30
). 如果您可以说服您的源提供ISO 8601格式的字符串(例如10:00
和19:30
),则是更好的选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.