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?

1

1 Answer 1

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".

Sign up to request clarification or add additional context in comments.

2 Comments

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)
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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.