0

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?

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • First, I strongly recommend that you avoid the `java.util.Date` and `SimpleDateFormat` classes. They were always very troublesome and are long outdated. Use `LocalDate` and `DateTimeFormatter` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/index.html). Second, I recommend you keep data model and presentation separate. Which day it is belongs in the model and is nicely represented by a `LocalDate`. For presentation convert the `LocalDate` back to a string to the user’s liking, for example `Apr 1, 2019`. – Ole V.V. Aug 05 '23 at 09:27

1 Answers1

2

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.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110