1

With the following formatter I'm able to parse "2017-03-28T23:40:06.000+0100"

new DateTimeFormatterBuilder()
            .append(ISO_LOCAL_DATE_TIME)
            .appendPattern("X")
            .toFormatter();

With another one it parses "2017-03-28T23:40:06.000+01:00"

new DateTimeFormatterBuilder()
            .append(ISO_LOCAL_DATE_TIME)
            .appendPattern("XX")
            .toFormatter();

However, I'm unable to specify formatter that parses both. What pattern should I append?

Formatter should also be able to process timestamps without zone-offset, e.g. "2017-03-28T23:40:06.000Z"

Michal Kordas
  • 10,475
  • 7
  • 58
  • 103

3 Answers3

1

Since the DateTimeFormatterBuilder behaves like a fluent interface, the easiest way is to append both of the patterns:

new DateTimeFormatterBuilder()
        .append(ISO_LOCAL_DATE_TIME)
        .appendPattern("X")
        .appendPattern("XX")
        .toFormatter();
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
1

The following started to work for me

new DateTimeFormatterBuilder()
            .append(ISO_LOCAL_DATE_TIME)
            .optionalStart()
            .appendPattern("[XXX][X]")
            .toFormatter();
Michal Kordas
  • 10,475
  • 7
  • 58
  • 103
0

I once had a task to parse any String to Date if the String represent a valid Date not knowing format in advance. Basically I needed to format String of any possible format. I came up with an idea where you write into a file all data formats that you wish to support and then read the formats one by one and try to parse a String by that format until you succeed or run out of formats. Here is the link to the article that describe the idea in more detail: Java 8 java.time package: parsing any string to date

Michael Gantman
  • 7,315
  • 2
  • 19
  • 36
  • I know format in advance, it must be ISO-valid format – Michal Kordas Apr 23 '19 at 09:18
  • Yes, I understand that you know in advance some limitations of your formats, but you can not create a single format that covers all possible options. Therefore you can apply the same idea as I suggested. Have several formats that together cover all valid options and try to parse your String with those formats one by one – Michael Gantman Apr 23 '19 at 09:49
  • That's exactly what I did, thanks. See my answer. – Michal Kordas Apr 23 '19 at 09:50