1

My app is calling up a Twitter feed and a blog feed, both contain a post date of course. When my phone is set to English locale it works, when I switch to Dutch or German it fails. The code in question does not even call upon the locale, and the input values are also independent of the locale.

The offending code:

tweets is a JSONObject containing the complete Twitter feed.

final SimpleDateFormat formatter = 
    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final SimpleDateFormat parser = 
    new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");

for (int i = 0; i < tweets.length(); i++) {
    final JSONObject tweet = tweets.getJSONObject(i);

    // The following line is where the failure occurs:
    values.put(KEY_TWEET_DATE, formatter.format(parser.parse(tweet
        .getString("created_at"))));
}

This works as long as my locale is English.

As soon as I switch to German or Dutch (my app contains translations for those two languages, I haven't tried any other so far) I get an error like this:

WARN/System.err(28273): java.text.ParseException: Unparseable date: Wed Jun 29 10:55:41 +0000 2011
WARN/System.err(28273):     at java.text.DateFormat.parse(DateFormat.java:645)
WARN/System.err(28273):     at squirrel.DeaddropDroid.DeaddropDB.updateTwitter(DeaddropDB.java:1453)

The "unparseable date" is the correct date, in the expected format. My format string is designed to parse that exact date. And as said, when I switch my phone to English locale, it works just fine. It's the same code: the error occurs even when I switch the locale while the app is running, and disappears when I switch back the locale.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Wouter
  • 2,623
  • 4
  • 34
  • 43

2 Answers2

4

If you need to parse in a particular locale, pass that into the SimpleDateFormat constructor:

final SimpleDateFormat parser =
    new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.US);

That means it will always use the US locale for day and month names etc.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • First comment edit failed :( Here we go again! - That's a very fast answer :) And totally correct. Just tested it, and it works. I never thought of locale influencing that one... thanks!! – Wouter Jun 29 '11 at 14:29
  • @AshishDwivedi: "not work" is far too vague for me to give any sort of answer, I'm afraid. I suspect it may be worth asking a new question though, making sure you give plenty of details. – Jon Skeet Apr 17 '13 at 13:30
1

Have you tried:

SimpleDateFormat parser = 
    new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy",Locale.getDefault());
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
tdtje
  • 190
  • 1
  • 8
  • Date/time string is from an external source, so has nothing to do with my device's locale. As in the accepted answer above it's indeed that I have to manually set the correct locale for parsing that string! – Wouter Jun 29 '11 at 14:31