Android implements data sorting by time

  • 2021-10-15 11:33:34
  • OfStack

I often meet the situation of one list and two interfaces, and the two interfaces belong to two different table data, so after the data is spliced back, it is not sorted according to time, and it looks quite chaotic, so record how to sort the data according to time under 1.

Step 1:

Formatting Date


public static Date stringToDate(String dateString) {
    ParsePosition position = new ParsePosition(0);
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date dateValue = simpleDateFormat.parse(dateString, position);
    return dateValue;
  }

Step 2:

Sort the spliced list


private void sortData(ArrayList<CourseModel> mList) {
    Collections.sort(mList, new Comparator<CourseModel>() {
      /**
       *
       * @param lhs
       * @param rhs
       * @return an integer < 0 if lhs is less than rhs, 0 if they are
       *     equal, and > 0 if lhs is greater than rhs, When comparing data sizes, , It's time here 
       */
      @Override
      public int compare(CourseModel lhs, CourseModel rhs) {
        Date date1 = DateUtil.stringToDate(lhs.getCREATE_TIME());
        Date date2 = DateUtil.stringToDate(rhs.getCREATE_TIME());
        //  To ascend the date field, if you want to descend, you can use after Method 
        if (date1.before(date2)) {
          return 1;
        }
        return -1;
      }
    });
    adapter.replaceAll(mList);
  }

Call this method directly, and the data type can be transformed by 1.


Related articles: