Java date time format pattern for ISO_OFFSET_DATE_TIME

前端 未结 3 654
旧时难觅i
旧时难觅i 2021-01-27 16:25

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

相关标签:
3条回答
  • 2021-01-27 16:47

    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.

    0 讨论(0)
  • 2021-01-27 16:56

    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
    
    0 讨论(0)
  • 2021-01-27 17:00

    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);
    
    0 讨论(0)
提交回复
热议问题