java.time.format.DateTimeParseException: Text could not be parsed at index 20

734 views Asked by At

java.time.format.DateTimeParseException: Text '2020-08-21T14:00:00.00+0700' could not be parsed at index 20 exception got for below code.

ZonedDateTime.parse(iso8601DateString, "yyyy-MM-dd'T'HH:mm:ss.SSSZ")

it worked in java 11 but it got exception in Java 17.

2

There are 2 answers

0
Shine On

Got it worked with 2020-08-21T14:00:00.000+0700, milliseconds should be three digit (000)

0
Arvind Kumar Avinash On

I recommend you use the following DateTimeFormatter which can serve for the varying number of digits in the fraction-of-second. It will also hold good when the second-of-minute (and hence the fraction-of-second too) part is absent.

DateTimeFormatter dtf = new DateTimeFormatterBuilder()
                        .append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
                        .appendPattern("Z")
                        .toFormatter(Locale.ENGLISH);

Alternatively, you can use DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSZ", Locale.ENGLISH) but this is just specific to the given date-time string.

Demo:

class Main {
    public static void main(String[] args) {
        String strDateTime = "2020-08-21T14:00:00.00+0700";

        // Recommended
        DateTimeFormatter dtf = new DateTimeFormatterBuilder()
                                .append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
                                .appendPattern("Z")
                                .toFormatter(Locale.ENGLISH);
        OffsetDateTime odt = OffsetDateTime.parse(strDateTime, dtf);
        System.out.println(odt);

        // Alternatively,
        dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSZ", Locale.ENGLISH);
        odt = OffsetDateTime.parse(strDateTime, dtf);
        System.out.println(odt);
    }
}

Output:

2020-08-21T14:00+07:00
2020-08-21T14:00+07:00

ONLINE DEMO

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