0

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)"

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Peter
  • 2,480
  • 6
  • 39
  • 60
  • I dnt think u search any thing ? – duggu Feb 15 '18 at 12:16
  • Your SimpleDateFormat doesn't specify a `Locale`, so it uses the system default, instead of `Locale.ENGLISH` – Peter Bruins Feb 15 '18 at 12:20
  • show the log of parsed date please – krishank Tripathi Feb 15 '18 at 12:23
  • As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Feb 15 '18 at 13:58
  • 1
    Possible duplicate of [Getting error java.text.ParseException: Unparseable date: (at offset 0) even if the Simple date format and string value are identical](https://stackoverflow.com/questions/46285384/getting-error-java-text-parseexception-unparseable-date-at-offset-0-even-if) – Ole V.V. Feb 15 '18 at 14:00

1 Answers1

1

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.

whtsido
  • 26
  • 1