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

后端 未结 2 1380
广开言路
广开言路 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.

    0 讨论(0)
  • 2021-01-14 19:38

    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)

    0 讨论(0)
提交回复
热议问题