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)
This should do it:
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:
A
LocalDateTimecannot have a format (itstoStringmethod invariably produces an ISO 8601 format). So to obtain a specific format you need to convert to aStringagain:This outputs:
(I hope you didn’t expect a
LocalDateTimewith the format you mentioned. In case you did see this question: Can’t rid of 'T' in LocalDateTime.)