简体   繁体   中英

Java date time format pattern for ISO_OFFSET_DATE_TIME

I'm after the date time format pattern for ISO_OFFSET_DATE_TIME

2019-09-30T10:05:16+10:00

yyyy-MM-dd'T'HH:mm:ssZ is valid for 2019-09-30T10:05:16+1000 but I need the colon in the zone offset

If this is not possible, I'll need a regular expression.

You need uuuu-MM-dd'T'HH:mm:ssXXX here.

String str = "2019-09-30T10:05:16+10:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssXXX");
OffsetDateTime datetime = OffsetDateTime.parse(str, formatter);
System.out.println(datetime);

It depends. DateTimeFormatter.ISO_OFFSET_DATE_TIME prints and parses strings with and without seconds and with and without fraction of second, the latter up to 9 decimals.

If you only need the pattern for the variant of the format given in your question, with seconds and without fraction of second, the answer by MC Emperor is exactly what you need.

If you need the full flexibility of ISO_OFFSET_DATE_TIME , then there is no pattern that can give you that. Then you will need to go the regular expression way. Which in turn can hardly give you as strict a validation as the formatter. And the regular expression may still grow complicated and very hard to read.

Link: My answer to a similar question with a few more details.

You can use yyyy-MM-dd'T'HH:mm:ssZZZZZ or uuuu-MM-dd'T'HH:mm:ssXXX .

Demo:

import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        String strDateTime = "2019-09-30T10:05:16+10:00";
        OffsetDateTime odt = OffsetDateTime.parse(strDateTime);
        // Default format i.e. OffsetDateTime#toString
        System.out.println(odt);

        // Custom format
        System.out.println(odt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZZZZZ")));
        System.out.println(odt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX")));
    }
}

Output:

2019-09-30T10:05:16+10:00
2019-09-30T10:05:16+10:00
2019-09-30T10:05:16+10:00

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