[英]Converting ISO 8601 timestamp String to java.time.OffsetDateTime
Let's say I have a date in ISO 8601 format: "2017-01-10T14:55:32+01:00"
.假设我有一个 ISO 8601 格式的日期:
"2017-01-10T14:55:32+01:00"
。
How do I convert it to OffsetDateTime ?如何将其转换为OffsetDateTime ?
I haven't found any answer here.我在这里没有找到任何答案。 I tried following:
我尝试了以下操作:
public OffsetDateTime stringToOffsetDateTime() {
return OffsetDateTime.from(Instant.parse("2019-12-12T10:39:40-02:00"));
}
But it throws DateTimeParseException
.但它抛出
DateTimeParseException
。
The shortest answer is:最短的答案是:
OffsetDateTime.parse("2017-01-10T14:55+01:00")
It recognizes ISO 8601 format by default (using DateTimeFormatter.ISO_DATE_TIME).它默认识别 ISO 8601 格式(使用 DateTimeFormatter.ISO_DATE_TIME)。
If needed, you can use other formaters in this way:如果需要,您可以通过这种方式使用其他格式化程序:
OffsetDateTime.parse(iso8601String, DateTimeFormatter.ISO_OFFSET_DATE);
All the formaters can be browsed here: https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html所有格式化程序都可以在这里浏览: https ://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
The attempt from OP has failed because formatter from Instant was used. OP 的尝试失败,因为使用了 Instant 的格式化程序。 This naturally failed because Instant is always in UTC so even if possible you'd loose time zone info.
这自然失败了,因为 Instant 总是在 UTC 中,所以即使可能你会丢失时区信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.