为适配器排序日期字符串

时间:2017-05-31 08:14:10

标签: java android

我有一个自定义对象,我以字符串的形式从中获取日期和时间。 它在for循环中。

List<MyObj> objs = getActivity().getPreferences().getData(activity);
for (MyObj myob : objs) {

int pos = adapter.contains(myob.id);
 if (pos == -1) {
          data = new MyAdapter.MyData();
          data.myob = myob;
          adapter.addItem(data);

         }
         else {
           data = adapter.getItem(pos);
              data.myob = myob;
         }

//Sorting to be done here... I get date from data.myob.date which returns String as 22.05 12:45
//After sorting, I need to notify the adapter.

adapter.notifyDataSetChanged();

}

现在我需要按升序和降序排序自定义对象的日期。 我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

试试这个

Collections.sort(yourList, new Comparator<CustomClass>() {
                        @Override
                        public int compare(CustomObject o1, CustomObject o2) {

                            DateFormat date = new SimpleDateFormat("dd MMM yyyy");
                            Date d1 = null, d2 = null;
                            try {
                                d1 = date.parse(o1.get_date().toString());
                                d2 = date.parse(o2.get_date().toString());

                            } catch (ParseException e) {
                                e.printStackTrace();
                            }

                            //return o1.get_date().compareTo(o2.get_date());
                            return d1.compareTo(d2);
                        }
                    });