roydbt
roydbt

Reputation: 101

java - Unparseable date when using SimpleDateFormat

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)

Upvotes: 1

Views: 344

Answers (1)

Anonymous
Anonymous

Reputation: 86399

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.

Upvotes: 3

Related Questions