package com.jt.dto;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* User: ldj
* Date: 2022/3/2
* Time: 22:48
* Description: No Description
*/
public class DateListSort {
public static void main(String[] args) {
ArrayList<Date> dates = new ArrayList<>();
dates.add(stringToDate("20230215"));
dates.add(stringToDate("20220302"));
dates.add(stringToDate("19951109"));
dates.add(stringToDate("20501123"));
ArrayList<String> beforeDateStrList = new ArrayList<>();
dates.forEach(date -> beforeDateStrList.add(dateToString(date)));
System.out.println("排序前:" + beforeDateStrList);
ArrayList<String> afterDateStrList = new ArrayList<>();
testSort(dates);//倒序
dates.forEach(date -> afterDateStrList.add(dateToString(date)));
System.out.println("排序后:" + afterDateStrList);
}
//String -> Date
public static Date stringToDate(String dateStr) {
Date date = null;
try {
SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
date = ft.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
//Date -> String
public static String dateToString(Date date) {
SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
return ft.format(date);
}
public static void testSort(List<Date> list) {
for (int i = 0; i < list.size() - 1; i++) {
for (int j = 1; j < list.size() - i; j++) {
if (list.get(i).before(list.get(i + j))) {
Date empty;
empty = list.get(i);
list.set(i, list.get(i + j));
list.set(i + j, empty);
}
}
}
}
}
|