1

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.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
shrek_23
  • 51
  • 1
  • 5
  • Semicolon is ISO timezone, try using X instead of Z, see here https://dzone.com/articles/java-simpledateformat-guide – Michal Krasny Oct 21 '20 at 07:16
  • Does this answer your question, in whole or in part? [What is the equivalent format string of DateTimeFormatter.ISO_OFFSET_DATE_TIME?](https://stackoverflow.com/questions/52619353/what-is-the-equivalent-format-string-of-datetimeformatter-iso-offset-date-time) – Ole V.V. Oct 21 '20 at 08:32

3 Answers3

3

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);
MC Emperor
  • 22,334
  • 15
  • 80
  • 130
0

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.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
0

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
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110