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

后端 未结 2 1379
广开言路
广开言路 2021-01-14 18:45

I have the following Java:

DateFormat formatter = new SimpleDateFormat(
    \"EEE MMM dd yyyy HH:mm:ss zZ (zzzz)\", Locale.ENGLISH);
Calendar cal = Calendar.         


        
2条回答
  •  北海茫月
    2021-01-14 19:27

    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.

提交回复
热议问题