java - 如何在列表日期中获取最大和最小日期就像 java 中的 String ''17.03.2020", ''12.03.2020", ''01.02.2020"
问题描述
List<String> dateList=new ArrayList<>();
请帮助我获取给定列表日期格式的最大和最小日期为字符串格式(“17.03.2020”)
解决方案
用于DateTimeFormatter
将日期字符串转换为相应的LocalDate
值并将它们添加到List
您可以使用排序的新值中Collections::sort
。
执行以下操作:
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);
}
}
输出:
[2020-02-01, 2020-03-12, 2020-03-17]
[01.02.2020, 12.03.2020, 17.03.2020]