Android:如何根据日期对列表项进行排序

时间:2013-10-24 08:19:54

标签: android

我有一个列表视图,其中包含许多包含日期的列表项。我想通过日期对项目进行排序,例如日期在当前日期之后的项目应该是第一个,而日期已过期的项目应该在之后。任何人都可以帮忙。

2 个答案:

答案 0 :(得分:10)

您可以使用自己的比较器

Collections.sort(yourList, new Comparator<YourObjectInYourList>() {
  public int compare(YourObjectInYourList o1, YourObjectInYourList o2) {
      if (o1.getDate() == null || o2.getDate() == null)
        return 0;
      return o1.getDate().compareTo(o2.getDate());
  }
});

答案 1 :(得分:0)

List<Date> dateList = new ArrayList<Date>();        
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy",Locale.US);    
try {
    dateList.add(sdf.parse("01/12/2013"));
    dateList.add(sdf.parse("02/11/2013"));
    dateList.add(sdf.parse("03/12/2013"));
    dateList.add(sdf.parse("04/10/2013"));
    dateList.add(sdf.parse("05/12/2013"));
    dateList.add(sdf.parse("06/12/2013"));      
    dateList.add(new Date());

    Collections.sort(dateList); 
    Comparator<Date> cmp = new Comparator<Date>() {

      @Override
      public int compare(Date o1, Date o2) {
        if(o1.getTime() > o2.getTime()) return 1;
        else if(o1.getTime() < o2.getTime()) return -1;
        else return 0;
      }             
    };

    Collator collator = Collator.getInstance();
    List<Date>  out_of_date_list = new ArrayList<Date>();
    for(Date date : dateList){
        System.out.println(">>> date = "+sdf.format(date));
        System.out.println(">>> out of date "+cmp.compare(new Date(), date));
            if(cmp.compare(date,new Date())<0){
                out_of_date_list.add(date);
            }           
    }
    System.out.println(">>> print all out of date ");           
    for(Date date : out_of_date_list){
       System.out.println(">>> date = "+sdf.format(date));      
    }               
} catch (ParseException e) {// TODO Auto-generated catch block 
    e.printStackTrace();        
}