How to sort array list by ascending and descending order by date in android.

This is simple, you just have to add below code in your activity or fragment where your arraylist is fetched from api or database. To perform sort on array list you have to use collections, please see below code.
Collections.sort(arrBook,byDate);


static final Comparator<Appointment> byDate = new Comparator<Appointment>() {
          // SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
          //  SimpleDateFormat sdf = new SimpleDateFormat(AppUtils.DateFormats.TIME_FORMAT_12);
          SimpleDateFormat sdf = new SimpleDateFormat(AppUtils.DateFormats.DATETIME_FORMAT_HISTORY_DISPLAY);

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

Comments