DateTimeFormatter Not Parsing String Correctly

DateTimeFormatter Not Parsing String Correctly

So I'm trying to parse a string from a file that looks like 2/1/2025 18:00

The code I have in place is:

private static final String DATE_FORMAT = "MM/dd/yyyy HH:mm";

....

Date date = Date.from(LocalDateTime.parse(record.get("start_date").toString(), DateTimeFormatter.ofPattern(DATE_FORMAT)).atZone(ZoneId.systemDefault()).toInstant()));

However, when I go to test this section of code out, it throws a DateTimeParseException:

java.time.format.DateTimeParseException: Text '2/1/2025 18:00' could not be parsed at index 0
   at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2046)
   ....

From a surface level glance, I believe I have the right format, but that appears to not be the case. Does anyone know what I may have gotten wrong here?

Answer

First of all, way too much code crammed on one line.

Secondly, your formatting pattern does not match your input.

Thirdly, do not mix the terribly flawed legacy classes with their modern replacement, java.time.

Your use of the double letters HH and dd means that you expect your inputs to pad any single digit numbers with a leading zero. Your example input does not meet that expectation. So use single-digit.

DateTimeFormatter f = DateTimeFormatter.ofPattern ( "M/d/uuuu HH:mm" ) ;

Parse your input as a LocalDateTime object because it lacks the context of an offset or time zone.

Use short simple lines of code. Easy to read and edit by humans, easy to optimize by the compiler and runtime.

LocalDateTime ldt = LocalDateTime.parse ( input , f ) ;

Apparently you want to assume that date and time represents a moment as seen in the current default time zone of the JVM. Thot seems risky to me, but here we go.

ZoneId z = ZoneId.systemDefault() ;
ZonedDateTime zdt = ldt.atZone ( z ) ;

Enjoyed this article?

Check out more content on our blog or follow us on social media.

Browse more articles