Why does this SimpleDataFormat parsing fail on Android?

前端 未结 2 1996
梦毁少年i
梦毁少年i 2021-01-13 06:38
DateFormat sdf = new SimpleDateFormat(\"EEE MMM d HH:mm:ss z yyyy\");

sdf.parse(\"Sun Dec 13 10:00:00 UTC 2009\")

result

ja

2条回答
  •  -上瘾入骨i
    2021-01-13 07:41

    It doesn't for me - perhaps your default locale uses different month names? Specify the locale for the format.

    // Will definitely work
    DateFormat sdf = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy",
                                          Locale.US);
    
    // Will definitely not work
    DateFormat sdf = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy",
                                          Locale.FRANCE);
    
    // Might work - depends on default locale
    DateFormat sdf = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy")
    

    (The problem is the names of the days of the week and months of the year, which are obviously culture-specific. Date and time separators can vary too.)

    EDIT: It's odd that you're still having problems. Just to check, please try to run the following short but complete program:

    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Locale;
    
    public class Test {
    
        public static void main(String[] args) throws Exception {        
            DateFormat sdf = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy",
                                                  Locale.US);
            sdf.parse("Sun Dec 13 10:00:00 UTC 2009");
        }
    }
    

    If that doesn't work, try taking out the time zone part of both the pattern and the text. I wonder whether it's having problems with that.

    EDIT: If the Android SimpleDateFormat implementation doesn't manage to parse the time zone, you can probably just use:

    text = text.replace(" UTC ", " ");
    Date parsed = sdf.parse(text);
    

    ... having set the time zone on the parser to UTC, of course. You probably want to check that it contains " UTC " first, just in case your data format changes.

提交回复
热议问题