SimpleDateFormat("MMM d, yyyy") returns Weekday Month day 00:00:00 EDT year

88 Views Asked by At

I have a String List [Apr 1, 2019, Aug 1, 2020, Feb 20, 2018] which i need to convert to Date format in the same pattern. When Im doing it with SimpleDateFormat("MMM d, yyyy") pattern Im getting Thu Aug 01 00:00:00 EDT 2019 format. Tried with Joda DateTimeFormatter and same result. Can anyone please help to resolve?

1

There are 1 best solutions below

0
Arvind Kumar Avinash On

java.time

The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API.

Also, quoted below is a notice from the home page of Joda-Time:

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

Your problem

You are trying to parse the date string into a java.util.Date object and print it. A java.util.Date object represents only the number of milliseconds since January 1, 1970, 00:00:00 GMT. When you print its object, the string returned by Date#toString, which applies your system's timezone, is printed. Note that a date-time object holds only date-time information, not a format. A format is represented using a string which you obtain by formatting the date-time object using a date-time formatting class with the desired pattern.

Solution using java.time, the modern Date-Time API:

public class Main {
    public static void main(String[] args) {
        List<String> list = List.of("Apr 1, 2019", "Aug 1, 2020", "Feb 20, 2018");
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM d, uuuu", Locale.ENGLISH);
        list.forEach(s -> {
            LocalDate date = LocalDate.parse(s, dtf);
            System.out.printf("Default format: %s, Custom format: %s%n", date, date.format(dtf));
        });
    }
}

Output:

Default format: 2019-04-01, Custom format: Apr 1, 2019
Default format: 2020-08-01, Custom format: Aug 1, 2020
Default format: 2018-02-20, Custom format: Feb 20, 2018

ONLINE DEMO

Note: Here, you can use y instead of u but I prefer u to y. Also, never use DateTimeFormatter for custom formats without a Locale.

Learn more about the modern Date-Time API from Trail: Date Time.