I am using the same pattern to both format and parse a LocalDateTime
object. However, parsing the formatted string is throwing a DateTimeParseException
. I created this mcve to demonstrate the issue:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-yyyy hh:mm:ss:nn");
LocalDateTime dateTime = LocalDateTime.of(2023, 1, 12, 10, 2, 7, 0);
String formatted = formatter.format(dateTime);
System.out.println(formatted);
LocalDateTime.parse(formatted, formatter);
The output is:
01-12-2023 10:02:07:00
Exception in thread "main" java.time.format.DateTimeParseException: Text '01-12-2023 10:02:07:00' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {MicroOfSecond=0, SecondOfMinute=7, HourOfAmPm=10, MilliOfSecond=0, NanoOfSecond=0, MinuteOfHour=2},ISO resolved to 2023-01-12 of type java.time.format.Parsed
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
at com.nhbb.router.drawing.DrawingManager.main(DrawingManager.java:45)
Caused by: java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {MicroOfSecond=0, SecondOfMinute=7, HourOfAmPm=10, MilliOfSecond=0, NanoOfSecond=0, MinuteOfHour=2},ISO resolved to 2023-01-12 of type java.time.format.Parsed
at java.time.LocalDateTime.from(LocalDateTime.java:461)
at java.time.format.Parsed.query(Parsed.java:226)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
... 2 more
Caused by: java.time.DateTimeException: Unable to obtain LocalTime from TemporalAccessor: {MicroOfSecond=0, SecondOfMinute=7, HourOfAmPm=10, MilliOfSecond=0, NanoOfSecond=0, MinuteOfHour=2},ISO resolved to 2023-01-12 of type java.time.format.Parsed
at java.time.LocalTime.from(LocalTime.java:409)
at java.time.LocalDateTime.from(LocalDateTime.java:457)
... 4 more
Looking at other answers on this site, it seems like this only should happen if a required temporal field is missing, such as year or month. All the required fields are present in the java.time.format.Parsed
instance shown in the output, so why is this code not working?