I want sort the ToDo list by date in ascending order. Can you help me, Im a beginner in android field enter link description here
Asked
Active
Viewed 4,231 times
-4
-
Welcome @santhosh karthik do some research before directly posting question here . this is surely a duplicate one . – ADM Jan 04 '18 at 13:07
-
You can find the answer for both ascending and descending here https://stackoverflow.com/a/66772568/5915318 – David Kariuki Mar 23 '21 at 23:21
2 Answers
7
Try this for ascending and descending order of date
Collections.sort(arrayList, byDate);
Method ascending and descending
static final Comparator<HomeModel> byDate = new Comparator<HomeModel>() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy,MM,dd");
public int compare(HomeModel ord1, HomeModel ord2) {
Date d1 = null;
Date d2 = null;
try {
d1 = sdf.parse(ord1.eventdate);
d2 = sdf.parse(ord2.eventdate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//return (d1.getTime() > d2.getTime() ? -1 : 1); //descending
return (d1.getTime() > d2.getTime() ? 1 : -1); //ascending
}
};

mehul chauhan
- 1,792
- 11
- 26
0
private void sortOldToNew() {
if (inspectionDataArrayList == null)
inspectionDataArrayList = new ArrayList<>();
Collections.sort(inspectionDataArrayList, new Comparator<ClsInspection>() {
public int compare(ClsInspection o1, ClsInspection o2) {
String strDt1 = o1.getInspectionDateTime(); // your first date here
String strDt2 = o2.getInspectionDateTime(); // second date here
if (Utility.isValueNull(strDt1) || Utility.isValueNull(strDt2))
return 0;
else {
Date dt1 = Utility.convertStringDateToDate(GMT_DATE_FORMAT, strDt1);
Date dt2 = Utility.convertStringDateToDate(GMT_DATE_FORMAT, strDt2);
if (dt1 == null || dt2 == null)
return 0;
return dt1.compareTo(dt2);
}
}
});
setAdapter(inspectionDataArrayList);
}
where , String GMT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

chandani c patel
- 309
- 3
- 9