简体   繁体   English

将 ISO 8601 时间戳字符串转换为 java.time.OffsetDateTime

[英]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.

相关问题 如何将java.sql.Timestamp转换为java.time.OffsetDateTime? - How to convert java.sql.Timestamp to java.time.OffsetDateTime? 无法从 openapi 客户端中的字符串反序列化“java.time.OffsetDateTime”类型的值 - Cannot deserialize value of type `java.time.OffsetDateTime` from String in openapi client 从 java.sql.Timestamp 转换为 ISO_OFFSET_DATE_TIME String,然后转换为 OffsetDateTime? - Convert from java.sql.Timestamp to ISO_OFFSET_DATE_TIME String then to OffsetDateTime? 将时间字符串转换为ISO 8601格式 - Converting a time String to ISO 8601 format 在SQLite数据库中存储java.time.OffsetDateTime的推荐方法 - Recommended way to store java.time.OffsetDateTime in SQLite Database 从ISO 8601日期字符串转换为BigQuery时间戳时出错 - Error when converting to BigQuery timestamp from ISO 8601 date string 在java中将iso8601日期转换为unix时间戳 - Converting iso8601 date to unix timestamp in java 如何将 org.threeten.bp.OffsetDateTime 转换为 java.time.OffsetDateTime? - How can I convert a org.threeten.bp.OffsetDateTime to java.time.OffsetDateTime? 将UTC ISO 8601字符串转换为毫秒可得到+12小时的时间 - Converting a UTC ISO 8601 string to milliseconds gives a time of +12 hours 将符合 ISO 8601 的字符串转换为 java.util.Date - Converting ISO 8601-compliant String to java.util.Date
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM