Search code examples
javaandroiddatesimpledateformatdatetime-parsing

SimpleDateFormat parse exception on Android 7+


I'm trying to parse a date and convert to a Timestamp.

On Android 6 it works, but on Android 7 it throws an exception. Can any tell me how to fix it?

private long getCorrectDate(String date) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'Z (z)");
    Date parsedDate = null;
    try {
        Logger.e("PARSE DATE : "+date);
        parsedDate = dateFormat.parse(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
    Logger.e("" + date + " TO " + timestamp.getTime());
    return timestamp.getTime();
}

java.text.ParseException: Unparseable date: "Thu Feb 15 2018 10:55:55 GMT+0000 (UTC)"


Solution

  • The input has English names for day of week and month, so you need to specify a java.util.Locale.

    If you create a SimpleDateFormat without a locale, it uses the device's default. Your code only works if the default is already English, otherwise you need to specify it:

    // use Locale.US or Locale.ENGLISH, I think both will work
    SimpleDateFormat dateFormat =
        new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'Z (z)", Locale.US);
    

    Actually, if you're sure that the input is always in English, use the corresponding locale instead of relying on the defaults.