Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this SimpleDataFormat parsing fail on Android?

DateFormat sdf = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy");

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

result

java.text.ParseException: Unparseable date: Sun Dec 13 10:00:00 UTC 2009

Note: This code seems to work in a normal Java application but seems to fail on Android.

like image 245
Sander Versluys Avatar asked Nov 08 '11 09:11

Sander Versluys


2 Answers

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.

like image 185
Jon Skeet Avatar answered Sep 25 '22 11:09

Jon Skeet


Your format looks correct. Is it possible that you are not using an English Locale though? The formatter will take your system locale and this could result in different names for 'sun' and 'dec'

like image 28
Thirler Avatar answered Sep 25 '22 11:09

Thirler