1

I am trying to convert an array of strings to a Date ArrayList with the following format - "dd/MM/yyyy" I have included my method below. When I print the ArrayList the dates are not formatted correctly and are displayed as: "Thu Mar 05 00:00:00 GMT 2020" Can anyone think why this is happening?

private void convertDates()
        {
            SimpleDateFormat formatter1=new SimpleDateFormat("dd/MM/yyyy");

            for (String dateString : date) {
                try {
                    dateList.add(formatter1.parse(dateString));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            displayDates.setText(Arrays.toString(dateList.toArray()));
        }
  • 2
    Date objects has no format themselves but they have a default format when converted to strings without using a formatter like you do in your code. If you want a specific format for your output then you need to use another date formatter (or reuse the one you have). – Joakim Danielson Apr 10 '20 at 13:14
  • 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 `LocalDate` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Apr 11 '20 at 14:30

1 Answers1

0

You have a list of Date objects, and when you format them to a string, they'll use their default formatting, regardless of the format you used to parse them. If you want to display them in that format, you'll have to do so explicitly. E.g.:

displayDates.setText(
    dateList.stream().map(formatter1::format).collect(Collectors.joining(","));
Mureinik
  • 297,002
  • 52
  • 306
  • 350