在Java中将日期列表排序为String

时间:2016-04-25 18:45:11

标签: java

我的arrayList中有一个日期列表作为String。我需要从此列表中获取最低日期值,然后与“dd-MM-yy”格式的日期进行比较。我怎样才能做到这一点??

这是我的代码::

List<String> dateList = new ArrayList<String>();
for(DailyDataReading ddr: finalResult){
    dateList.add(sdf.format(ddr.getDailyReadingDate()));
}

Collections.sort(dateList);

if((sdf.format("date which is to be compared")).compareTo(dateList.get(dateList.size()-1))<=0)
 {...}

3 个答案:

答案 0 :(得分:1)

List<String> dateList;// This is your list of dates in string format
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yy");// This is a formatter to convert from your pattern to a LocalDate
List<LocalDate> dates = dateList.stream().map(dateString -> LocalDate.parse(dateString, dateTimeFormatter)).collect(Collectors.toList());// Use Java 8 streams to map the dates strings to LocalDate objects
Collections.sort(dates);// Sort the list
LocalDate earliestDate = dates.get(0);// Take the lowest date value from the list
LocalDate specialDate = LocalDate.parse("some date", dateTimeFormatter);// create a date object for the date that you want to compare it to
earliestDate.compareTo(specialDate);// compare them

答案 1 :(得分:0)

如果您的字符串都是dd-MM-yy形式的所有日期值,并且您希望按时间顺序对这些日期字符串进行排序,假设所有年份都是本世纪(即2000 - 2099年),那么这是你是怎么做的。

Collections.sort(dateList, (d1,d2) -> {
    int cmp = d1.substring(6, 8).compareTo(d2.substring(6, 8));
    if (cmp == 0)
        cmp = d1.substring(3, 5).compareTo(d2.substring(3, 5));
    if (cmp == 0)
        cmp = d1.substring(0, 2).compareTo(d2.substring(0, 2));
    return cmp;
});

“此列表中的最低日期值”是第一个值,即dateList.get(0)

答案 2 :(得分:0)

  

Collections.sort(list_of_dates,new CustomComparator());

public class CustomComparator implements Comparator<MyObject> {// MyObject would be Model class
    Date date1,date2;
    @Override
    public int compare(MyObject obj1, MyObject obj2) {
        DateFormat df1 = new SimpleDateFormat("dd, MMM yyyy");
        try {
             date1 = df1.parse(obj1.getDate());
             date2 = df1.parse(obj2.getDate());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date1.compareTo(date2);
    }
}

Collections.reverse(list_of_dates);

这将按照最新的顺序对您的列表进行排序..