[java] How to Sort Date in descending order From Arraylist Date in android?

I have an ArrayList which stores Dates and I sorted them in descending order. Now I want to display them in a ListView. This is what I did so far:

 spndata.setOnItemSelectedListener(new OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int position, long arg3) {

                switch (position) {
                case 0:
                    list = DBAdpter.requestUserData(assosiatetoken);
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(i).lastModifiedDate != null) {
                            lv.setAdapter(new MyListAdapter(
                                    getApplicationContext(), list));
                        }
                    }
                    break;
                case 1:
                    list = DBAdpter.requestUserData(assosiatetoken);

                    Calendar c = Calendar.getInstance();
                    SimpleDateFormat df3 = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");    
                    String formattedDate3 = df3.format(c.getTime());                        
                    Log.v("log_tag", "Date  " + formattedDate3);

                    for (int i = 0; i < list.size(); i++) {                         
                        if (list.get(i).submitDate != null) {                               
                            String sDate = list.get(i).submitDate;                              
                            SimpleDateFormat df4 = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");    
                            String formattedDate4 = df4.format(sDate);

                            Map<Date, Integer> dateMap = new TreeMap<Date, Integer>(new Comparator<Date>(){  
                                 public int compare(Date formattedDate3, Date formattedDate4) {
                                     return formattedDate3.compareTo(formattedDate4);
                                 }
                            });
                            lv.setAdapter(new MyListAdapter(
                                    getApplicationContext(), list));
                        }
                    }
                    break;
                case 2:

                    break;

                case 3:

                    break;

                default:
                    break;
                }

            }

            public void onNothingSelected(AdapterView<?> arg0) {
            }

        });

This question is related to java android date arraylist sortedlist

The answer is


If date in string format convert it to date format for each object :

String argmodifiledDate = "2014-04-06 22:26:15";
SimpleDateFormat  format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
            try
            {
                this.modifiledDate = format.parse(argmodifiledDate);
            }
            catch (ParseException e)
            {

                e.printStackTrace();
            }

Then sort the arraylist in descending order :

ArrayList<Document> lstDocument= this.objDocument.getArlstDocuments();
        Collections.sort(lstDocument, new Comparator<Document>() {
              public int compare(Document o1, Document o2) {
                  if (o1.getModifiledDate() == null || o2.getModifiledDate() == null)
                    return 0;     
                  return o2.getModifiledDate().compareTo(o1.getModifiledDate());
              }
            });

Easier alternative to above answers

  1. If Object(Model Class/POJO) contains the date in String datatype.

    private void sortArray(ArrayList<myObject> arraylist) {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); //your own date format
    if (reports != null) {
        Collections.sort(arraylist, new Comparator<myObject>() {
            @Override
            public int compare(myObject o1, myObject o2) {
                try {
                    return simpleDateFormat.parse(o2.getCreated_at()).compareTo(simpleDateFormat.parse(o1.getCreated_at()));
                } catch (ParseException e) {
                    e.printStackTrace();
                    return 0;
                }
            }
        });
    }
    
  2. If Object(Model Class/POJO) contains date in Date datatype

    private void sortArray(ArrayList<myObject> arrayList) {
    if (arrayList != null) {
        Collections.sort(arrayList, new Comparator<myObject>() {
            @Override
            public int compare(myObject o1, myObject o2) {
                return o2.getCreated_at().compareTo(o1.getCreated_at()); }
        });
    } }
    

The above code is for sorting the array in descending order of date, swap o1 and o2 for ascending order.


Date's compareTo() you're using will work for ascending order.

To do descending, just reverse the value of compareTo() coming out. You can use a single Comparator class that takes in a flag/enum in the constructor that identifies the sort order

public int compare(MyObject lhs, MyObject rhs) {

    if(SortDirection.Ascending == m_sortDirection) {
        return lhs.MyDateTime.compareTo(rhs.MyDateTime);
    }

    return rhs.MyDateTime.compareTo(lhs.MyDateTime);
}

You need to call Collections.sort() to actually sort the list.

As a side note, I'm not sure why you're defining your map inside your for loop. I'm not exactly sure what your code is trying to do, but I assume you want to populate the indexed values from your for loop in to the map.


Date is Comparable so just create list of List<Date> and sort it using Collections.sort(). And use Collections.reverseOrder() to get comparator in reverse ordering.

From Java Doc

Returns a comparator that imposes the reverse ordering of the specified comparator. If the specified comparator is null, this method is equivalent to reverseOrder() (in other words, it returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface).


Just add like this in case 1: like this

 case 0:
     list = DBAdpter.requestUserData(assosiatetoken);
     Collections.sort(list, byDate);
     for (int i = 0; i < list.size(); i++) {
         if (list.get(i).lastModifiedDate != null) {
             lv.setAdapter(new MyListAdapter(
                     getApplicationContext(), list));
         }
     }
     break;

and put this method at end of the your class

static final Comparator<All_Request_data_dto> byDate = new Comparator<All_Request_data_dto>() {
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");

    public int compare(All_Request_data_dto ord1, All_Request_data_dto ord2) {
        Date d1 = null;
        Date d2 = null;
        try {
            d1 = sdf.parse(ord1.lastModifiedDate);
            d2 = sdf.parse(ord2.lastModifiedDate);
        } 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
    }
};

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to arraylist

Adding null values to arraylist How to iterate through an ArrayList of Objects of ArrayList of Objects? Dynamically adding elements to ArrayList in Groovy How to replace existing value of ArrayList element in Java How to remove the last element added into the List? How to append elements at the end of ArrayList in Java? Removing Duplicate Values from ArrayList How to declare an ArrayList with values? In Java, can you modify a List while iterating through it? Load arrayList data into JTable

Examples related to sortedlist

lists and arrays in VBA How to Sort Date in descending order From Arraylist Date in android? Get random sample from list while maintaining ordering of items? What's the difference between SortedList and SortedDictionary?