I've been looking around but can't find any example usage of offset O in the timestamp schema as described in https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html.
From the above doc:
Offset O: This formats the localized offset based on the number of pattern letters. One letter outputs the short form of the localized offset, which is localized offset text, such as 'GMT', with hour without leading zero, optional 2-digit minute and second if non-zero, and colon, for example 'GMT+8'. Four letters outputs the full form, which is localized offset text, such as 'GMT, with 2-digit hour and minute field, optional second field if non-zero, and colon, for example 'GMT+08:00'. Any other count of letters throws IllegalArgumentException.
The notable section here is that "one letter outputs the short form e.g. 'GMT+8' and that four letters outputs the full form e.g. 'GMT+08:00'". So I tried writing up some tests using this information from the doc:
val dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSO")
dtf.parse("2020-01-01T00:00:00.000GMT+8") // fails
...
val dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSOOOO")
dtf2.parse("2020-01-01T00:00:00.000GMT+08:00") // fails
They both fail with e.g.:
[info] java.time.format.DateTimeParseException: Text '2020-01-01T00:00:00.000GMT+8' could not be parsed: String index out of range: 28
[info] at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
[info] at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1781)
[info] ...
[info] Cause: java.lang.StringIndexOutOfBoundsException: String index out of range: 28
[info] at java.lang.String.charAt(String.java:658)
[info] at java.time.format.DateTimeFormatterBuilder$LocalizedOffsetIdPrinterParser.getDigit(DateTimeFormatterBuilder.java:3526)
[info] at java.time.format.DateTimeFormatterBuilder$LocalizedOffsetIdPrinterParser.parse(DateTimeFormatterBuilder.java:3588)
[info] at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.parse(DateTimeFormatterBuilder.java:2219)
[info] at java.time.format.DateTimeFormatter.parseUnresolved0(DateTimeFormatter.java:2010)
[info] at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1939)
[info] at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1777)
I've also tried using 2020-01-01T00:00:00.000 GMT+8 as an input. Am I just using this wrong?
tl;dr
Details
The Javadoc says:
So, a single
Oformatting code character handles, for example,GMT+8. Wow, just what you asked for!Rather than create the entire formatting pattern by hand, we can leverage the existing formatter
ISO_LOCAL_DATE_TIME. Append ourOto that formatter by way ofDateTimeFormatterBuilder.