1

Jira is giving me this date format via Rest API:
2021-01-21T11:08:45.000+0100

How can i parse this to a LocalDateTime in Java?

I tried

ZonedDateTime.parse("2021-01-21T11:08:45.000+0100", DateTimeFormatter.ISO_OFFSET_DATE_TIME);

Or this:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
ZonedDateTime.parse("2021-01-21T11:08:45.000+0100"), formatter);

The result is DateTimeParseException

Thomas Lang
  • 1,285
  • 17
  • 35
  • 1
    Your string contains a UTC offset (`+0100`) , not a time zone. So unless you have very specific requirements, prefer to parse into an `OffsetDateTime`, not a `ZonedDateTime`. – Ole V.V. Jan 22 '21 at 12:26
  • 1
    Does this answer your question? [Cannot parse String in ISO 8601 format, lacking colon in offset, to Java 8 Date](https://stackoverflow.com/questions/43360852/cannot-parse-string-in-iso-8601-format-lacking-colon-in-offset-to-java-8-date) – Ole V.V. Jan 22 '21 at 12:27
  • Or does this? [Parse date string without losing timezone in Groovy for Jira](https://stackoverflow.com/questions/53948091/parse-date-string-without-losing-timezone-in-groovy-for-jira). I figure it should be straightforward to translate the code from [the answer by daggett](https://stackoverflow.com/a/53948810/5772882) to Java. – Ole V.V. Jan 22 '21 at 12:36
  • Thank you @OleV.V. Your second comment does the trick. Nevertheless i had to use the given formatter of that link. So both solutions work, your suggestion and the selected answer. – Thomas Lang Jan 25 '21 at 07:18

1 Answers1

2

Since the zone offset in your value is in the format +0100, it cannot be parsed with any of the predefined formatters like DateTimeFormatter.ISO_OFFSET_DATE_TIME, as it expects it to be in the format +01:00

You can parse 2021-01-21T11:08:45.000+0100 with the pattern "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

ZonedDateTime.parse("2021-01-21T11:08:45.000+0100", DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"))

The reference for DateTimeFormatter is here.

Madhu Bhat
  • 13,559
  • 2
  • 38
  • 54