只需调用getSortedDateList
方法即可根据您的要求对日期进行排序
private ArrayList<Date> getSortedDateList(ArrayList<Date> dateList) {
//Replace year with current year to sort in jan to dec order
for(int i = 0; i < dateList.size(); i++) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateList.get(i));
calendar.set(Calendar.YEAR, Calendar.getInstance().get(Calendar.YEAR));
dateList.set(i, calendar.getTime());
}
//Sort all dates in ascending order
Collections.sort(dateList);
//Get final index of past dates
int index = 0;
for (int i = 0; i < dateList.size(); i++) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateList.get(i));
calendar.set(Calendar.YEAR, Calendar.getInstance().get(Calendar.YEAR));
Calendar today = Calendar.getInstance();
today.set(Calendar.DATE, Calendar.getInstance().get(Calendar.DATE) - 1);
if (calendar.getTime().after(today.getTime())) {
index = i;
break;
}
}
//New list for storing upcoming dates
ArrayList<Date> newList = new ArrayList<>();
//Store upcoming dates in new list
for (int i = index; i < dateList.size(); i++) {
newList.add(dateList.get(i));
}
//Store past dates in new list
for (int i = 0; i < index; i++) {
newList.add(dateList.get(i));
}
Collections.copy(dateList, newList);
return dateList;
}
例如,将一些示例日期存储到数组列表并调用getSortedDateList
方法
SimpleDateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy"); // Your date format
ArrayList<Date> dateList = new ArrayList<>();
dateList.add(formatter.parse("Thu May 25 00:00:00 GMT+05:30 2000"));
dateList.add(formatter.parse("Tue Apr 18 00:00:00 GMT+05:30 2021"));
dateList.add(formatter.parse("Wed Jan 27 00:00:00 GMT+05:30 1997"));
dateList.add(formatter.parse("Sat Feb 22 00:00:00 GMT+05:30 2020"));
dateList.add(formatter.parse("Mon Dec 20 00:00:00 GMT+05:30 2001"));
dateList.add(formatter.parse("Thu Jun 14 00:00:00 GMT+05:30 2009"));
dateList.add(formatter.parse("Sat Mar 01 00:00:00 GMT+05:30 1999"));
dateList.add(formatter.parse("Sat Nov 07 00:00:00 GMT+05:30 2005"));
dateList = getSortedDateList(dateList);
for(Date date: dateList) {
System.out.println(date.toString());
}
如果当前日期是Feb 01 2021
,那么最终输出将如下所示
Mon Feb 22 00:00:00 IST 2021
Mon Mar 01 00:00:00 IST 2021
Sun Apr 18 00:00:00 IST 2021
Tue May 25 00:00:00 IST 2021
Mon Jun 14 00:00:00 IST 2021
Sun Nov 07 00:00:00 IST 2021
Mon Dec 20 00:00:00 IST 2021
Wed Jan 27 00:00:00 IST 2021