Pan Charles
Pan Charles

Reputation: 21

Why does this code generate the error: "unparseable date"

I'm trying to use the SimpleDateFormat class to parse a DateTime out of this string:

Mon Jan 10 2011 01:15:00 GMT+0000 (GMT Standard Time)

I tried the following format string:

String example = "Mon Jan 10 2011 01:15:00 GMT+0000 (GMT Standard Time)";
SimpleDateFormat formatter = new SimpleDateFormat("E M d y H:m:s z");
try
{
    Date exampleDate = formatter.parse(example);
    LOGGER.warn(exampleDate.toString());
}
catch(Exception e)
{
    LOGGER.warn(e.getMessage(), e);
}

But it generates the error:

Unparseable date: "Mon Jan 10 2011 01:15:00 GMT+0000 (GMT Standard Time)"

So I tried removing the parenthesized end part of the example string:

String example = "Sun Jan 09 2011 22:00:00 GMT+0000";

But it generates the same error.

WARNING: Unparseable date: "Sun Jan 09 2011 22:00:00 GMT+0000"
java.text.ParseException: Unparseable date: "Sun Jan 09 2011 22:00:00 GMT+0000"

Any hints on how to get around this?

Upvotes: 2

Views: 4746

Answers (4)

Frederick Nyawaya
Frederick Nyawaya

Reputation: 2305

You should use (or Z only for last part):

E MMM dd yyyy HH:mm:ss zZ 

Upvotes: 2

Cameron Skinner
Cameron Skinner

Reputation: 54376

You also need to use "MMM" if you want to parse textual months. From the javadocs:

"Month: If the number of pattern letters is 3 or more, the month is interpreted as text; otherwise, it is interpreted as a number."

Upvotes: 1

templatetypedef
templatetypedef

Reputation: 372982

I think that the problem is that the z modifier can't parse GMT+0000. According to the Javadoc describing what z parses, the format is something like GMT+HH:MM, rather than GMT+HHMM. If you want to parse what you have, you probably want to change your format string from

E M d y H:m:s z

to

E M d y H:m:s 'G'M'Tz

Upvotes: 0

Evan Mulawski
Evan Mulawski

Reputation: 55334

According to http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html the format needs to be:

"E M d y H:m:s zZ"

This includes the general timezone and the RFC 822 time zone.

Or you could change your input date to:

Mon Jan 10 2011 01:15:00 GMT+00:00

which would accomodate just z.

(Note the colon in the last part.)

Upvotes: 2

Related Questions