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!
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.
Your own code: Thank you for providing your own code in the comment under this answer. For other readers I am repeating it here, formatted for readability.
fun parseZonedDateTimeToString(date: ZonedDateTime): String {
return DateTimeFormatter.ISO_ZONED_DATE_TIME.format(date)
}
fun parseStringToZonedDateTime(dateString: String): ZonedDateTime {
return ZonedDateTime.parse(dateString, DateTimeFormatter.ISO_ZONED_DATE_TIME)
}
Links
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 stringsDateTimeFormatter.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]'.”