I'm trying to move from Joda to Java 8's ZonedDateTime and I'm hitting a wall with the DateTimeFormatterBuilder that I cannot seem to work around.
I want to accept any of these formats:
2013-09-20T07:00:33
2013-09-20T07:00:33.123
2013-09-20T07:00:33.123+0000
2013-09-20T07:00:33.123Z
2013-09-20T07:00:33.123Z+0000
2013-09-20T07:00:33+0000
Here is my current builder:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
.optionalStart()
.appendPattern(".SSS")
.optionalEnd()
.optionalStart()
.appendZoneId()
.optionalEnd()
.optionalStart()
.appendPattern("Z")
.optionalEnd()
.toFormatter();
I'm probably wrong, but it appears that should match the patterns I want... right?
If anyone could point of what I may have missed, it'd be appreciated. I'm also not too sure of the use of appendOffset, so clarity on that is also appreciated if it turns out to be the answer.
Edit:
Text '2013-09-20T07:00:33.061+0000' could not be parsed at index 23
Looking at the builder, this appears to match due to the optional stages?
Edit 2:
After seeing advice from the first answer, I tried this:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
.optionalStart()
.appendPattern(".SSS")
.optionalEnd()
.optionalStart()
.appendZoneOrOffsetId()
.optionalEnd()
.toFormatter()
It continues to fail on the string above.
Edit 3:
Latest tests result in this exception:
java.time.format.DateTimeParseException: Text '2013-09-20T07:00:33.061+0000' could not be parsed at index 23
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1947)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1849)
at java.time.ZonedDateTime.parse(ZonedDateTime.java:597)
at java.time.ZonedDateTime.parse(ZonedDateTime.java:582)