1

I'm trying to read data from RSS feeds and one of the fields is when the feed was last updated. I'm using something similar to this:

Date date;
String output;
SimpleDateFormat formatter;

String pattern = "EEE, dd MMM, HH:mm:ss Z";

formatter = new SimpleDateFormat(pattern, Locale.ENGLISH);
date = formatter.parse("Wed, 25 Mar 2020 08:00:00 +0200");
output = date.toString();
System.out.println(pattern + " | " + output);

but I get this error:

Exception in thread "main" java.text.ParseException: Unparseable date: "Wed, 25 Mar 2020 08:00:00 +0200"
at java.text.DateFormat.parse(DateFormat.java:366)
at HelloWorld.main(HelloWorld.java:16)
2
  • 5
    The string you are trying to parse does not match the format string. The year yyyy is missing in the format string. There is also a comma after the month which is not in your input string. Try this: EEE, dd MMM yyyy HH:mm:ss Z Commented Mar 25, 2020 at 14:02
  • 1
    I recommend you don’t use SimpleDateFormat and Date. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use OffsetDateTime and DateTimeFormatter, both from java.time, the modern Java date and time API. Commented Mar 25, 2020 at 14:18

1 Answer 1

3

java.time

java.time is the modern java date and time API and has a built-in formatter for your string:

    String lastUpdatedString = "Wed, 25 Mar 2020 08:00:00 +0200";
    OffsetDateTime dateTime = OffsetDateTime
            .parse(lastUpdatedString, DateTimeFormatter.RFC_1123_DATE_TIME);
    System.out.println(dateTime);

Output:

2020-03-25T08:00+02:00

So there’s no need to write our own format pattern string, which is always error-prone, and certainly no need to use the SimpleDateFormat class. That class is a notoriously troublemaker of a class, so we had wanted to avoid it anyway.

Link: Oracle tutorial: Date Time explaining how to use java.time.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.