0

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.

nuhkoca
  • 1,777
  • 4
  • 20
  • 44
  • You can improve your question by replacing `Timer.d()` with `System.out.println()` or `Log.d`, there is no need to pull a third-party library into this. Best provide a [MVCE](https://stackoverflow.com/help/mcve) – leonardkraemer Oct 24 '18 at 16:56
  • Thanks, @leonardkraemer, sorry this code was taken from a corporate project. – nuhkoca Oct 24 '18 at 17:23

1 Answers1

2

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"

Community
  • 1
  • 1
leonardkraemer
  • 6,573
  • 1
  • 31
  • 54
  • Hi @leonardkraemer I tried your solution however it threw below error: Text '2018-10-24T16:37:32.693Z' could not be parsed at index 2 – nuhkoca Oct 24 '18 at 16:39
  • Dont mind the `java.time` imports I tried it on android with actual ThreeTenABP – leonardkraemer Oct 24 '18 at 17:00
  • Hi @leonardkraemer, Yeah it works. You saved my day! Thanks ahead. I accepted the answer :) Good day! – nuhkoca Oct 24 '18 at 17:22
  • Hi @leonardkraemer, Last question :) Whatever I have any pattern, it always gives me same output. For instance, I set a pattern like "dd MM yyyy EEEE" and I am expecting an output 20 October 2018 Wednesday but it always give 2018-10-20 – nuhkoca Oct 24 '18 at 17:50