问题
I have this date:
"Wed Dec 31 00:00:00 GMT-8 1969"
But it cannot be parsed with this SimpleDateFormat:
new SimpleDateFormat("EEE MMM dd hh:mm:ss zzz yyyy");
How do I specify the -8
in the format string? I have tried Z
and X
after reading the SDF docs, but to no avail. What should I use?
回答1:
The use of -8
is in a non ISO standard format.
Something like -0800
or -08:00
is expected. This is because the time offset can include half hours.
You should run a preprocessing conversion on the string before passing it to the SimpleDateFormat and change it to "Wed Dec 31 00:00:00 GMT-0800 1969"
and use:
new SimpleDateFormat("EEE MMM dd hh:mm:ss Z yyyy");
If you want to make it simpler just create a method to replace the -8
with America/Los_Angeles
and use ZZZ
.
回答2:
If you are using java 8, you can try DateTimeFormatter
with a pattern of "EEE MMM d HH:mm:ss O yyyy"
likes:
String date = "Wed Dec 31 00:00:00 GMT-8 1969";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM d HH:mm:ss O yyyy");
LocalDateTime dateTime = LocalDateTime.parse(date, formatter);
O
represent localized zone-offset and can format zone offset like GMT+8, GMT+08:00, UTC-08:00. You can see Offset O
in DateTimeFormatter for more details.
来源:https://stackoverflow.com/questions/38277202/how-to-parse-timezone-with-single-digit-offset-wed-dec-31-000000-gmt-8-1969