Why run the following commands: cannot a date string be parsed as OffsetDateTime ?
String inputOdt = "2016-01-23T12:34:56 GMT+8"; DateTimeFormatter formatterOdt = DateTimeFormatter.ofPattern ( "yyyy-MM-dd'T'HH:mm:ss O" ); OffsetDateTime odt = OffsetDateTime.parse ( inputOdt , formatterOdt );
Using Java(TM) SE Runtime Environment (build 1.8.0_92-b14) on Mac OS X El Capitan 10.11.4.
Generates an error:
Exception in thread "main" java.time.format.DateTimeParseException: text '2016-01-23T12: 34: 56 GMT + 8' cannot be parsed: row index out of range: 25
offset-from-UTC string GMT+8 copied-pasted from an example in the class documentation for DateTimeFormatter . Quote:
Offset O: Formats a localized offset based on the number of letters of the patterns. One letter displays a short form of a localized offset, which is a localized offset text such as "GMT", with an hour without a leading zero, an optional 2-digit minute and second if non-zero, and a colon, for example, "GMT + 8" " .
The rest of the string is successfully processed as LocalDateTime . So the problem seems to really be part of the bias from UTC.
String inputLdt = "2016-01-23T12:34:56"; DateTimeFormatter formatterLdt = DateTimeFormatter.ofPattern ( "yyyy-MM-dd'T'HH:mm:ss" ); LocalDateTime ldt = LocalDateTime.parse ( inputLdt , formatterLdt ); System.out.println ( "" ); System.out.println ( "inputLdt: " + inputLdt ); System.out.println ( "ldt: " + ldt );
inputLdt: 2016-01-23T12: 34: 56
ldt: 2016-01-23T12: 34: 56
Bypass
A partial workaround is to add a trailing space to both the input string and the formatting pattern. So it works.
String input = "Sat May 02 2015 00:00:00 GMT+08 "; // Trailing space. DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "EEE MMM dd yyyy HH:mm:ss O " ); // Trailing space. OffsetDateTime odt = OffsetDateTime.parse ( input , formatter ); // SUCCEEDS
But adding minutes without a colon is documented as working with one O , but it fails. This workaround for the trailing space in this case does not help. Pay attention to GMT+0800 in this example compared to GMT+08 , as shown above, where this example failed, but the above result succeeds.
String input = "Sat May 02 2015 00:00:00 GMT+0800 "; // Minutes in the offset, and trailing space. DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "EEE MMM dd yyyy HH:mm:ss O " ); // Trailing space. OffsetDateTime odt = OffsetDateTime.parse ( input , formatter ); // FAILS