0

I am trying to parse an ISO8601 time string of format "yyyy-MM-dd'T'HH:mm:ssZ" using the below line for ZonedDateTime object:

ZonedDateTime date = ZonedDateTime.parse("2021-02-19T14:32:12+0000", DateTimeFormatter.ISO_ZONED_DATE_TIME);

However I am getting the below error when doing this:

java.time.format.DateTimeParseException: Text '2021-02-19T14:32:12+0000' could not be parsed at index 19

I cant imagine this is not allowed as the + symbol is a valid character for the parse. Can anyone assist on what is wrong here?

MisterIbbs
  • 247
  • 1
  • 7
  • 20
  • [My answer here](https://stackoverflow.com/a/66232081/5772882) might be helpful? Or this question; [Convert a string to ZonedDateTime](https://stackoverflow.com/questions/61269697/convert-a-string-to-zoneddatetime). – Ole V.V. Feb 19 '21 at 15:21

1 Answers1

2

That is because ISO_ZONED_DATE_TIME expects both an offset and a zone. See edit, it is not required in all cases. It is because the offset must contain a colon.

See the docs.

Use DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssxx", Locale.ROOT) instead. Alternatively, you could use the DateTimeFormatterBuilder:

new DateTimeFormatterBuilder()
    .append(DateTimeFormatter.ISO_DATE_TIME)
    .appendPattern("xx")
    .toFormatter(Locale.ROOT);

Edit

Only reading the summary fragment of the Javadoc is apparently not enough. The zone id is not strictly required by the ISO_ZONED_DATE_TIME, as mentioned in the comments. The second bullet point there mentions it: "If the zone ID is not available or is a ZoneOffset then the format is complete".

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
  • Thank you, this approach works and I opted to use the older format syntax as the offset needs to have the 4 digits present rather than two. DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ", Locale.ROOT) – MisterIbbs Feb 19 '21 at 14:54
  • `ISO_ZONED_DATE_TIME` lives happily without the zone ID. The documentation that you link to says that *If the zone ID is not available … then the format is complete* after the zone offset. The real problem was the lack of colon in the offset. You are correct that `xx` in the format pattern string solves it (no matter if using a builder or not). – Ole V.V. Feb 19 '21 at 15:17