首页 > 解决方案 > 如何在 Android Studio 的自定义 Arraylist 中对日期进行排序?

问题描述

我在我的应用程序中添加了一项功能,该功能允许用户填写过去日期的条目,如果今天是 2020 年 3 月 14 日,那么它可以让您填写 2020 年 3 月 10 日(或任何其他日期)的条目。但是我在对我的数组列表进行排序时遇到问题,这样所有具有相同日期的条目都在数组列表中。

我在自定义 ListView 中向用户显示条目,因此为了使我的应用程序用户友好,我想让所有具有相同日期的条目一起出现。

我有一个自定义数组列表,它接受费用名称(字符串)、金额(字符串)和日期(字符串)

ArrayList<ExpenseData> customArrayList=new ArrayList<ExpenseData>();

如果您需要任何其他信息,请询问...谢谢!

标签: javaandroidandroid-studio

解决方案


您可以使用以下方法按日期对列表进行排序。

 Collections.sort(list, (item1, item2) -> {
            Date date1 = stringToDate(item1.getDate());
            Date date2 = stringToDate(item2.getDate());

            if (date1 != null && date2 != null) {
                boolean b1;
                boolean b2;
                if (isAscending) {
                    b1 = date2.after(date1);
                    b2 = date2.before(date1);
                }else {
                    b1 = date1.after(date2);
                    b2 = date1.before(date2);
                }

                if (b1 != b2) {
                    if (b1) {
                        return -1;
                    }
                    if (!b1) {
                        return 1;
                    }
                }
            }
            return 0;
        });

public static Date stringToDate(String strDate) {
        if (strDate == null)
            return null;

        // change the date format whatever you have used in your model class.
        SimpleDateFormat format = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a", Locale.US);
        Date date = null;
        try {
            date = format.parse(strDate);
            System.out.println(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

推荐阅读