Java 8 DateTimeParseException,当使用DateTimeFormatter解析AM / PM时间时
我正在尝试使用Java 8将格式化的字符串解析为对象。但是,我在解析某些输入字符串时遇到了一些问题。当我的输入字符串具有“AM”时,它会正确解析,但是当我的字符串具有“PM”时,它会引发异常。下面是一个简单的示例:java.time.format.DateTimeFormatter
java.time.LocalTime
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class FormatterExample {
private static final DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm a");
public static void main(String[] args) {
parseDateAndPrint("08:06 AM");
parseDateAndPrint("08:06 PM");
}
public static void parseDateAndPrint(String time) {
LocalTime localTime = LocalTime.parse((time), timeFormatter);
System.out.println(localTime.format(timeFormatter));
}
}
输出:
08:06 AM
Exception in thread "main" java.time.format.DateTimeParseException: Text '08:06 PM' could not be parsed: Conflict found: Field AmPmOfDay 0 differs from AmPmOfDay 1 derived from 08:06
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1919)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1854)
at java.time.LocalTime.parse(LocalTime.java:441)
at FormatterExample.parseDateAndPrint(FormatterExample.java:11)
at FormatterExample.main(FormatterExample.java:8)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: java.time.DateTimeException: Conflict found: Field AmPmOfDay 0 differs from AmPmOfDay 1 derived from 08:06
at java.time.format.Parsed.crossCheck(Parsed.java:582)
at java.time.format.Parsed.crossCheck(Parsed.java:563)
at java.time.format.Parsed.resolve(Parsed.java:247)
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1954)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1850)
... 8 more
因此被正确解析,但会抛出带有消息的 DateTimeParseException:08:06 AM
08:06 PM
Text '08:06 PM' could not be parsed: Conflict found: Field AmPmOfDay 0 differs from AmPmOfDay 1 derived from 08:06
但这就是我陷入困境的地方。我不太确定这个错误到底是什么意思,但它肯定与输入字符串的AM / PM部分有关。我也尝试搜索类似的错误,但我无法找到任何东西。我有一种感觉,我在这里定义格式化程序模式时可能会犯一个简单的错误,但我卡住了。任何帮助将不胜感激!