Java Date Parsing Timezone causing parsing error

I am getting a ParseException with the following code and I cannot fix it:

String date = "Tue Mar 13 2012 10:48:05 GMT-0400";
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss zzzX"); //Tried zzzZ at the end as well
System.out.println(format.parse(date));

      

If I take out -0400 and the X (or Z) at the end of the SimpleDateFormat works fine, but once it's in the code, it just doesn't work. What character should I use instead? I am using Java 7.

Below is the parse error:

java.text.ParseException: Unparseable date: "Tue Mar 13 2012 10:48:05 GMT-0400"
at java.text.DateFormat.parse(DateFormat.java:357)
java.text.ParseException: Unparseable date: "Tue Mar 13 2012 10:48:05 GMT-0400"
at java.text.DateFormat.parse(DateFormat.java:357)
at com.throwaway.parse.DateParsing.testDate(TestDate:17)

      

+3


source to share


5 answers


Part of GMT

GMT-0400

your line is causing the problem.
The parameter Z

(or X

in java 7) only matches -4000

. You should exit GMT

using single quotes like this:

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

      



Note that it is also recommended to set Local

in your DateFormat. Without that, your code won't work in other countries (like here in France ...).

+2


source


Three problems with mixed use. Or:

  • Use a single lowercase "z" and ":" separating your hour and time in your time zone when using "GMT (+/-) hh: mm" or
  • Use one uppercase "Z" and drop "GMT" from your timezone and you can use the format "(+/-) hhmm" or
  • Use one uppercase "X" and still leave "GMT", but you can use any hhmm zone format.


From the Javadoc:

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


source


The template zzzz

can handle strings of the "GMT-04: 00" style. Your example can be parsed using this template:EEE MMM dd yyyy HH:mm:ss Z

0


source


use "EEE MMM dd yyyy HH:mm:ss zzzZ"

.
zzz

for GMT

and Z

for 'RFC 822 time zone'

, please refer

check it

0


source


If you always expect your timezone to be represented this way, you can put "GMT" in single quotes in the format string to prevent parsing:

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

      

It's a bit strange that none of the built-in formats can parse it. Perhaps the Javadoc is incorrect when it lists GMT-08:00

as an example z

?

0


source







All Articles