2015-12-23 35 views
3

ArrayList<D> details;從列表中找到最近的日期

public class D { 
    String time; 
} 

我想找到最接近當前日期&時間,它應該給我在哪個位置是最近的。

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

試試這個http://stackoverflow.com/questions/5927109/sort-objects-in-arraylist-by-date – santoXme

回答

2

你可以嘗試使用以下功能:

請確保你必須通過Date對象(List<Date>),而不是你ArrayList<D> detailsList。您可以使用SimpleDateFormatString轉換爲Date

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); 
} 
相關問題