-2
List<String> dateList=new ArrayList<>();

Please help me hopw to get max and min dates in a given list date format is in String format("17.03.2020")

  • 1
    What have you tried yourself? Did you do any research? – jasie Mar 19 '20 at 07:53
  • Does this answer your question? [How to sort Date which is in string format in java?](https://stackoverflow.com/questions/14451976/how-to-sort-date-which-is-in-string-format-in-java) – Ole V.V. Mar 19 '20 at 15:26

1 Answers1

2

Use DateTimeFormatter to convert the date strings to the corresponding LocalDate values and add them to a new List which you can sort using Collections::sort.

Do it as follows:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Testing {
    public static void main(String[] args) {
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd.MM.uuuu");
        List<String> strDateList = new ArrayList<String>();
        strDateList.add("17.03.2020");
        strDateList.add("12.03.2020");
        strDateList.add("01.02.2020");

        List<LocalDate> dateList = new ArrayList<LocalDate>();
        for (String ds : strDateList) {
            dateList.add(LocalDate.parse(ds, dateFormatter));
        }
        Collections.sort(dateList);
        System.out.println(dateList);

        // If you want to replace the elements in the original list with sorted values
        strDateList.clear();
        for (LocalDate ld : dateList) {
            strDateList.add(ld.format(DateTimeFormatter.ofPattern("dd.MM.uuuu")));
        }
        System.out.println(strDateList);
    }
}

Output:

[2020-02-01, 2020-03-12, 2020-03-17]
[01.02.2020, 12.03.2020, 17.03.2020]
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110