Published 08 Sep, 2022

Java - Java LocalDateTime Text could not be parsed at index 0 exception

Category Java
Modified : Oct 04, 2022
91

Trying to convert a date which is in String format to Java LocalDateTime.

private DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
private String caseStartDate = dateFormat.format(LocalDateTime.now());

LocalDateTime localdatetime = LocalDateTime.parse(caseStartDate);

But ends up having this exception:

java.time.format.DateTimeParseException: Text '01/03/2020 15:13' could not be parsed at index 0

Doesnt this format support for conversion?

Answers

There are 1 suggested solutions here and each one has been listed below with a detailed description. The following topics have been covered briefly such as Java, Localdatetime. These have been categorized in sections for a clear and precise explanation.

34

You need to use your format inside LocalDateTime::parse as follows:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

class Main {
    public static void main(String[] args) {
        DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
        String caseStartDate = dateFormat.format(LocalDateTime.now());
        System.out.println(caseStartDate);
        LocalDateTime localdatetime = LocalDateTime.parse(caseStartDate, dateFormat);
        System.out.println(localdatetime);
    }
}

Output:

01/05/2020 09:13
2020-05-01T09:13

Also, see how the toString() method of LocalDateTime has been overridden:

@Override
public String toString() {
    return date.toString() + 'T' + time.toString();
}