Java Date Parsing Timezone causing parse error

拈花ヽ惹草 提交于 2019-12-06 02:05:32

The GMT part of GMT-0400 of your string is causing the problem.
The Z (or X in java 7) parameter is only matching -4000. You have to escape GMT by using single quotes like this :

DateFormat format = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'Z", Locale.US);

Note that it's also a good practice to put a Local in your DateFormat. Without it your code won't work in other countries (like here in France...).

Three issues all dealing with mixed usage. Either:

  1. Use a single lower-case "z" and a ":" separating your hour and time in the time zone when using "GMT(+/-)hh:mm", or
  2. Use a single upper-case "Z" and drop the "GMT" from your timezone, and you can use the "(+/-)hhmm" format, or
  3. Use a single upper-case "X" and still drop the "GMT" but you can use any format of the hhmm zone.

From the Javadoc:

  • z General time zone Pacific Standard Time; PST; GMT-08:00
  • Z RFC 822 time zone -0800
  • X ISO 8601 time zone -08; -0800; -08:00

The pattern zzzz could only parse "GMT-04:00" style strings. Your example can be parsed with this pattern: EEE MMM dd yyyy HH:mm:ss Z

use "EEE MMM dd yyyy HH:mm:ss zzzZ".
zzz is for GMT and Z is for 'RFC 822 time zone' please refer

Check this out

If you always expect your timezone to be represented that way, you could put "GMT" in single quotes in your format string to prevent it from being parsed:

EEE MMM dd yyyy HH:mm:ss 'GMT'XX

It's a bit weird that none of the built-in formats can parse it though. Perhaps the Javadoc is incorrect when it lists GMT-08:00 as an example of z?

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