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")
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")
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]