How to convert string to LocalDateTime,how to solve string format "yyyymmddhhMMss" to LocalDateTime

709 Views Asked by At

How to convert string to LocalDateTime,how to solve string format "yyyymmddhhMMss" to LocalDateTime

String dateTime = "20221120000000";

LocalDateTime localDateTime = LocalDateTime.parse(dateTime);


Exception in thread "main" java.time.format.DateTimeParseException: Text '20221120000000' could not be parsed at index 0
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1948)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1850)
    at java.time.LocalDateTime.parse(LocalDateTime.java:492)
    at java.time.LocalDateTime.parse(LocalDateTime.java:477)
    at com.company.Main.main(Main.java:21)
1

There are 1 best solutions below

1
z3fq0n On

This should do it:

String dateTimeString = "20221120000000";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);

If you dont want to use the DateTimeFormatter, your String needs to be in ISO format

Edit: it isn’t in the question, but you said elsewhere:

I want it to convert to this format("yyyy-MM-dd HH:mm:ss") …

A LocalDateTime cannot have a format (its toString method invariably produces an ISO 8601 format). So to obtain a specific format you need to convert to a String again:

DateTimeFormatter wantedFormatFormatter
        = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
String formattedDateTime = dateTime.format(wantedFormatFormatter);
System.out.println(formattedDateTime);

This outputs:

2022-11-20 00:00:00

(I hope you didn’t expect a LocalDateTime with the format you mentioned. In case you did see this question: Can’t rid of 'T' in LocalDateTime.)