list<Dtae>的集合里有一堆Thu Mar 27 16:01:41 CST 2031格式的日期,按照时间排序并取最大值给endDate取最小值给beginDate
时间: 2024-04-29 09:22:50 浏览: 52
java 中List按照date排序的实现
假设要排序的日期集合为dates,可以按照以下步骤操作:
1. 首先将日期字符串转换为Date类型,并存储到新的集合dateList中:
```java
List<Date> dateList = new ArrayList<>();
for (String dateStr : dates) {
try {
Date date = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US).parse(dateStr);
dateList.add(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
```
2. 对dateList进行排序:
```java
Collections.sort(dateList);
```
3. 取最大值作为endDate:
```java
Date endDate = dateList.get(dateList.size() - 1);
```
4. 取最小值作为beginDate:
```java
Date beginDate = dateList.get(0);
```
完整代码示例:
```java
List<String> dates = new ArrayList<>();
dates.add("Thu Mar 27 16:01:41 CST 2031");
dates.add("Fri Mar 28 11:22:33 CST 2031");
dates.add("Sat Mar 29 09:05:59 CST 2031");
List<Date> dateList = new ArrayList<>();
for (String dateStr : dates) {
try {
Date date = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US).parse(dateStr);
dateList.add(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
Collections.sort(dateList);
Date endDate = dateList.get(dateList.size() - 1);
Date beginDate = dateList.get(0);
System.out.println("endDate: " + endDate);
System.out.println("beginDate: " + beginDate);
```
输出结果:
```
endDate: Sat Mar 29 09:05:59 CST 2031
beginDate: Thu Mar 27 16:01:41 CST 2031
```
阅读全文