从列表中找到最近的日期

时间:2015-12-23 07:14:40

标签: android sorting

我有ArrayList<D> details;

public class D {
    String time;
}

我想找到最接近当前日期&amp;时间,它应该给我在哪个位置,它是最近的。

 private Date getDateNearest(List<Date> dates, Date targetDate) {
    Date returnDate = targetDate;
    for (Date date : dates) {
        // if the current iteration'sdate is "before" the target date
        if (date.compareTo(targetDate) <= 0) {
            // if the current iteration's date is "after" the current return date
            if (date.compareTo(returnDate) > 0) {
                returnDate = date;
            }
        }
    }
    return returnDate;
}

1 个答案:

答案 0 :(得分:2)

您可以尝试使用以下功能:

请确保您必须传递ListDate个对象(List<Date>)而不是ArrayList<D> details。您可以使用StringDate转换为SimpleDateFormat

  public void getNearestDate(List<Date> dates, Date targetDate) {
    Date nearestDate = null;
    int index = 0;
    long prevDiff = -1;
    long targetTS = targetDate.getTime();
    for (int i = 0; i < dates.size(); i++) {
        Date date = dates.get(i);
        long currDiff = Math.abs(date.getTime() - targetTS);
        if (prevDiff == -1 || currDiff < prevDiff) {
            prevDiff = currDiff;
            nearestDate = date;
            index = i;
        }
    }
    System.out.println("Nearest Date: " + nearestDate);
    System.out.println("Index: " + index);
}