-3

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)
melo
  • 5
  • 2
  • Your `String` is not of a standard/ISO format, you will have to create a custom `DateTimeFormatter` for that to work… – deHaar Dec 05 '22 at 08:25
  • Does this answer your question? [How can I parse/format dates with LocalDateTime? (Java 8)](https://stackoverflow.com/questions/22463062/how-can-i-parse-format-dates-with-localdatetime-java-8) – Chaosfire Dec 05 '22 at 08:37
  • 1
    Did you search? It’s a good question in that you are clear about what you want and the exception you observe (with nicely formatted stack trace). But your question appears poorly researched. You are supposed to search and research before asking a question here, and I frankly think you would have found stuff to help you solve your problem. (I neither downvoted nor voted to close. I see that others did.) – Ole V.V. Dec 05 '22 at 09:30

1 Answers1

1

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.)

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
z3fq0n
  • 19
  • 3
  • I made an addition to your answer that I think should be helpful for the OP. If you don’t like it, please revert my edit. – Ole V.V. Dec 05 '22 at 17:56