Date parsing in Java using SimpleDateFormat

Tags: , , , ,



I want to parse a date in this format: “Wed Aug 26 2020 11:26:46 GMT+0200” into a date. But I don’t know how to do it. I tried this:

SimpleDateFormat parser = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss z");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = parser.parse(split[0]); //error line
String formattedDate = formatter.format(date);

I am getting this error: Unparseable date: “Wed Aug 26 2020 11:26:46 GMT+0200”. Is my date format wrong? And if so could somebody please point me in the right direction?

Answer

I suggest you stop using the outdated and error-prone java.util date-time API and SimpleDateFormat. Switch to the modern java.time date-time API and the corresponding formatting API (java.time.format). Learn more about the modern date-time API from Trail: Date Time.

import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        // Given date-time string
        String dateTimeStr = "Wed Aug 26 2020 11:26:46 GMT+0200";

        // Parse the given date-time string to OffsetDateTime
        OffsetDateTime odt = OffsetDateTime.parse(dateTimeStr,
                DateTimeFormatter.ofPattern("E MMM d u H:m:s zX", Locale.ENGLISH));

        // Display OffsetDateTime
        System.out.println(odt);
    }
}

Output:

2020-08-26T11:26:46+02:00

Using the legacy API:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class Main {
    public static void main(String[] args) throws ParseException {
        // Given date-time string
        String dateTimeStr = "Wed Aug 26 2020 11:26:46 GMT+0200";

        // Define the formatter
        SimpleDateFormat parser = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'Z", Locale.ENGLISH);

        // Parse the given date-time string to java.util.Date
        Date date = parser.parse(dateTimeStr);
        System.out.println(date);
    }
}

Output:

Wed Aug 26 10:26:46 BST 2020


Source: stackoverflow