How to Parse Timezone with Single Digit Offset? “Wed Dec 31 00:00:00 GMT-8 1969”

安稳与你 提交于 2019-12-13 14:12:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!