What is the correct formatting pattern for this String format?

Benny :

I am getting a DateTimeParseException when trying to convert a String to a ZonedDateTime with threeten. I am not sure what the correct formatting pattern is for this String format? 2014-04-16T00:00+02:00[Europe/Berlin]. Can someone tell me how the correct pattern is?

On a sitenote: Is there some page or some resource somewhere where I can look such things up without having to reconstruct it by myself?

Thanks!

Ole V.V. :

No formatter needed: Your format is the default format for a ZonedDateTime. ZonedDateTime both parses and prints this format as its default, that is, without any explicit formatter.

    String s = "2014-04-16T00:00+02:00[Europe/Berlin]";
    ZonedDateTime zdt = ZonedDateTime.parse(s);
    System.out.println("Parsed into " + zdt);

Output:

Parsed into 2014-04-16T00:00+02:00[Europe/Berlin]

The format is extended from ISO 8601 format. ISO 8601 would be 2014-04-16T00:00+02:00 only, so includes the UTC offset but not the time zone. The developers of java.time extended it to include the time zone ID.

If you want a formatter: If you have a special reason for wanting a formatter, maybe you need to pass one to a method or you just wish to make it explicit which format you expect, one is built in: DateTimeFormatter.ISO_ZONED_DATE_TIME. So you still don’t need to write any format pattern string.

Where to find this information? It’s in the documentation of the classes of java.time. See the documentation links below.

Links

  • Wikipedia article: ISO 8601
  • Documentation links:
    • The one-arg ZonedDateTime.parse() specifying “a text string such as 2007-12-03T10:15:30+01:00[Europe/Paris]
    • ZonedDateTime.toString() promising “a String, such as 2007-12-03T10:15:30+01:00[Europe/Paris]
    • DateTimeFormatter with the built-in formatters as well as the pattern letters used in format pattern strings
    • DateTimeFormatter.ISO_ZONED_DATE_TIME, “The ISO-like date-time formatter that formats or parses a date-time with offset and zone, such as '2011-12-03T10:15:30+01:00[Europe/Paris]'.”
    • Since the links above are to the documentation of the Java 10 versions of the classes, which is not always identical to the documentation of the backport, here is the documentation of ThreeTen backport 1.4.2 API, under which you will find all of the above items too.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=409253&siteId=1