0

I'm trying to parse this date

Thu, 15 Nov 2018 16:56:49 +0000

With this code:

Date date = null;

try {
    SimpleDateFormat parser = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
    date = parser.parse(xmlPullParser.nextText());
    } catch (ParseException e) {
        e.printStackTrace();
        date = new Date(); //This is just a temporary workaround
    }

java.text.ParseException: Unparseable date: "Thu, 15 Nov 2018 16:56:49 +0000"

I've already try this formats too

EEE, dd MMM yyyy HH:mm:ss sssZ

EEE, d MMM yyyy HH:mm:ss sssZ

EEE, d MMM yyyy HH:mm:ss Z

But obviously it doesn't work

Community
  • 1
  • 1
  • how is the `xmlPullParser.nextText()`? are you sure that `nextText` can generate your expected output? – chenzhongpu Nov 26 '18 at 11:55
  • I recommend you avoid the `SimpleDateFormat` class. It is not only long outdated, it is also notoriously troublesome. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). It even has the format you are trying to parse built-in and knows that it is in English no matter the JVM’s locale setting. `OffsetDateTime.parse("Thu, 15 Nov 2018 16:56:49 +0000", DateTimeFormatter.RFC_1123_DATE_TIME)` yields an `OffsetDateTime` of `2018-11-15T16:56:49Z`. – Ole V.V. Nov 26 '18 at 12:12

1 Answers1

3

You forgot to set the Locale of SimpleDateFormat. Since you try to read a date in a english form, I would initialize this way:

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

When you don't specify any Locale, it uses the Locale of your system which is obviously not US or UK.

LaurentG
  • 11,128
  • 9
  • 51
  • 66