简体   繁体   中英

Java - unparseable date, need format to match “GMT-0400”

I have the following Java:

DateFormat formatter = new SimpleDateFormat(
    "EEE MMM dd yyyy HH:mm:ss zZ (zzzz)", Locale.ENGLISH);
Calendar cal = Calendar.getInstance();
cal.set(2011, Calendar.APRIL, 1);
out.println(formatter.format(cal.getTime()));
out.println();

Date date;
try {
    date = formatter
        .parse("Fri Apr 01 2011 00:00:00 GMT-0400 (Eastern Daylight Time)");
} catch (ParseException e) {
    out.println("Failed to parse date: " + e.getMessage());
    e.printStackTrace(out);
}

This is in a servlet, and the Calendar -constructed date comes out as:

Fri Apr 01 2011 16:42:24 EDT-0400 (Eastern Daylight Time)

This looks like the same format as the date string I'm trying to parse, except for EDT-0400 versus the desired GMT-0400 . The code fails when trying to parse the date string:

java.text.ParseException: Unparseable date: "Fri Apr 01 2011 00:00:00 GMT-0400 (Eastern Daylight Time)"

How can I parse such a string? This is coming from a JavaScript date in a Sencha Touch 1.1.1 model, stored in WebSQL local storage.

For some reason GMT-0400 isnt' working, and UTC-0400 is working. You can replace GMT with UTC.

Note that this part will be completely ignored - the timezone will be resolved from what's found in the brackets (at least on my machine, JDK 6)

I debugged SimpleDateFormat and it seems that it will only parse GMT-04:00 but not GMT-0400 .

It will accept UTC-0400 , however it will throw away the hours/minutes modifier and will incorrectly parse it as UTC . (This happens with any other timezone designation, except for GMT )

It will also parse -0400 correctly, so the most robust solution is probably to simply remove GMT from your date string.

The upshot of the story is that SimpleDateFormat is anything but simple.

Update: Another lesson is that I could've saved a lot of time by passing a ParsePosition object to the parse() method:

    DateFormat formatter = new SimpleDateFormat(
        "EEE MMM dd yyyy HH:mm:ss zzzz", Locale.ENGLISH);
    Date date;
    ParsePosition pos = new ParsePosition( 0 );
    date = formatter
        .parse("Fri Apr 01 2011 00:00:00 UTC-0400", pos);
    System.out.println( pos.getIndex() );

Will print out 28 , indicating that the parsing ended at character index 28, just after UTC .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM