简体   繁体   中英

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" .

How do I convert it to 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 .

The shortest answer is:

OffsetDateTime.parse("2017-01-10T14:55+01:00")

It recognizes ISO 8601 format by default (using 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

The attempt from OP has failed because formatter from Instant was used. This naturally failed because Instant is always in UTC so even if possible you'd loose time zone info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM