Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse offset with colon using DateTimeFormatter?

I have the following string: String timeStamp = "2020-01-31 12:13:14 +03:00". And I tried to parse it using Java 8 DateTimeFormatter.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern( format );
tmpTimestamp = ZonedDateTime.parse( timeStamp, formatter );

where format is one of:

"yyyy-MM-dd' 'HH:mm:ss' 'Z",
"yyyy-MM-dd' 'HH:mm:ss' 'X",
"yyyy-MM-dd' 'HH:mm:ss' 'x",
"yyyy-MM-dd HH:mm:ss Z",
"yyyy-MM-dd HH:mm:ss X",
"yyyy-MM-dd HH:mm:ss x",

None is working. Always I got DateTimeParseException either pointing to '+' or to ':' character in offset substring "+03:00"

According to JavaDocs: Class DateTimeFormatter "+03:00" shall be supported by any of: Z, X and x.

So the question is how to construct formatter string to parse it?

like image 701
Seweryn Habdank-Wojewódzki Avatar asked Apr 09 '19 18:04

Seweryn Habdank-Wojewódzki


1 Answers

From the javadoc

Offset Z: This formats the offset based on the number of pattern letters. One, two or three letters outputs the hour and minute, without a colon, such as '+0130'. The output will be '+0000' when the offset is zero. Four letters outputs the full form of localized offset, equivalent to four letters of Offset-O. The output will be the corresponding localized offset text if the offset is zero. Five letters outputs the hour, minute, with optional second if non-zero, with colon. It outputs 'Z' if the offset is zero. Six or more letters throws IllegalArgumentException.

You need 5 Z's

String format = "yyyy-MM-dd HH:mm:ss ZZZZZ";

Demo

like image 106
Savior Avatar answered Oct 04 '22 04:10

Savior