nuhkoca
nuhkoca

Reputation: 1943

Text could not be parsed at index 33

I am working on ThreeTenABP library to parse date and time. However, it is crashing. API I consume sends DateTime like;

2018-10-20T14:27:47.3949709+03:00

This is the way I try to parse;

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                .append(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
                .append(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
                .toFormatter();

Timber.d(LocalDateTime.parse("2018-10-20T14:27:47.3949709+03:00", formatter).toString());

I am getting below error:

Text '2018-10-20T14:27:47.3949709+03:00' could not be parsed at index 33

Thanks in advance.

Upvotes: 0

Views: 657

Answers (1)

leonardkraemer
leonardkraemer

Reputation: 6813

Explanation of the error message:

2018-10-20T14:27:47.3949709+03:00 is 33 chars long, therefore

Text '2018-10-20T14:27:47.3949709+03:00' could not be parsed at index 33

means it expected a 34th char which is not there (it's 0 indexed).

Problem

The way you defined the Formatter it would accept 2018-10-20T14:27:47.3949709+03:002018-10-20`

Solution:

To overcome this you can either drop the .append(DateTimeFormatter.ofPattern("yyyy-MM-dd")

Or define a Formatter that accepts both formats with startOptional and endOptional

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    .optionalStart()
    .append(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
    .optionalEnd()
    .optionalStart()
    .append(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"))
    .optionalEnd().toFormatter();

You can see the example working at https://ideone.com/RDVHYG

Side note: "yyyy-MM-dd" does not yield enough information for a LocalDateTime therefore I added "HH:mm"

Upvotes: 2

Related Questions