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?
You should use the times X
(yyyy-MM-dd HH:mm:ss XXX
):
String timeStamp = "2020-01-31 12:13:14 +03:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss XXX");
ZonedDateTime tmpTimestamp = ZonedDateTime.parse(timeStamp, formatter);
From the docs:
Offset X and x: This formats the offset based on the number of pattern letters.
One letter outputs just the hour, such as '+01', unless the minute is non-zero in which case the minute is also output, such as '+0130'.
Two letters outputs the hour and minute, without a colon, such as '+0130'.
Three letters outputs the hour and minute, with a colon, such as '+01:30'.
Four letters outputs the hour and minute and optional second, without a colon, such as '+013015'.
Five letters outputs the hour and minute and optional second, with a colon, such as '+01:30:15'.
Six or more letters throws IllegalArgumentException.
Pattern letter 'X' (upper case) will output 'Z' when the offset to be output would be zero, whereas pattern letter 'x' (lower case) will output '+00', '+0000', or '+00:00'.
Alternative you can use five letters (XXXXX
) and you also can use ZZZ
or ZZZZZ
instead of XXX
or XXXXX
.