I am trying to use Java 8 java.time.format.DateTimeFormatter to parse a formatted string into a java.time.LocalTime object. However, I am facing some problems parsing some input lines. When my input line has "AM", it parses correctly, but when my line has "PM", it throws an exception. Here is a simple example:
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)); } }
Conclusion:
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
So, 08:06 AM parsed correctly, but 08:06 PM throws a DateTimeParseException message with the message:
Text '08:06 PM' could not be parsed: Conflict found: Field AmPmOfDay 0 differs from AmPmOfDay 1 derived from 08:06
But this is where I got stuck .. I'm not quite sure what this error means for sure, but it is definitely related to the AM / PM part of my input string. I also tried to find similar errors, but I could not find anything. I have a feeling that I'm probably making a simple mistake here when I define my formatting pattern, but I'm stuck. Any help would be appreciated!
source share