Scott
Scott

Reputation: 9488

Java Date Parsing Timezone causing parse error

I'm receiving a ParseException with the following code and I can't seem to 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 the -0400 and the X (or Z) at the end of the SimpleDateFormat things work fine, but once it's in the code, it simply doesn't work. What symbol should I be using instead? I'm using Java 7.

Here is the parse error I receive:

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)

Upvotes: 3

Views: 4515

Answers (5)

Spencer Kormos
Spencer Kormos

Reputation: 8451

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

Upvotes: 2

matts
matts

Reputation: 6897

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?

Upvotes: 0

YCI
YCI

Reputation: 369

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...).

Upvotes: 2

shams.haq
shams.haq

Reputation: 714

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

Upvotes: 0

jabal
jabal

Reputation: 12367

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

Upvotes: 0

Related Questions