Unable to convert String to LocalDateTime format "YYYYMMDDhhmmss" (week year) pattern with (day of month)

123 Views Asked by At

I'm getting the "DateTimeParseException" when parsing the given String:

I know using 'yyyy' and 'dd' are suggested on some questions, but i can't use them. I use JDK 17

import java.time.format.DateTimeFormatter;
import java.time.*;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYYMMDDhhmmss");
LocalDateTime date = LocalDateTime.parse("20120823151034", formatter);

Result:

Exception in thread "main" java.time.format.DateTimeParseException: Text '20120823151034' could not be parsed at index 0
1

There are 1 best solutions below

1
Arvind Kumar Avinash On

I know using 'yyyy' and 'dd' are suggested on some questions, but i can't use them.

Not only 'yyyy' and 'dd', you also need to use 'HH' instead of 'hh' because 'hh' makes sense only with am/pm marker i.e. for a 12-hour time format. For a time with an am/pm marker, you need to use 'hh' along with 'a' e.g. 'hhmmss a'. Check the documentation to learn more about them.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
LocalDateTime dt = LocalDateTime.parse("20120823151034", formatter);
System.out.println(dt);

Output from a sample run:

2012-08-23T15:10:34

Online Demo

Learn more about the modern Date-Time API from Trail: Date Time.