我如何找到指定日期的最近日期?(JAVA)

Con*_*ure 7 java methods date closest

我希望知道如何键入一个方法来给我一个指定日期的最接近日期.我的意思是以下内容:

public Date getNearestDate(List<Date> dates, Date currentDate) {
    return closestDate  // The date that is the closest to the currentDate;
}
Run Code Online (Sandbox Code Playgroud)

我发现了类似的问题,但只有一个有一个很好的答案,代码一直给我NullPointerExceptions ...任何人都可以帮助我吗?

mae*_*ics 14

您可以通过计算时间差(例如Date#getTime())并返回最小值来在线性时间内求解:

public static Date getNearestDate(List<Date> dates, Date currentDate) {
  long minDiff = -1, currentTime = currentDate.getTime();
  Date minDate = null;
  for (Date date : dates) {
    long diff = Math.abs(currentTime - date.getTime());
    if ((minDiff == -1) || (diff < minDiff)) {
      minDiff = diff;
      minDate = date;
    }
  }
  return minDate;
}
Run Code Online (Sandbox Code Playgroud)

[编辑]

轻微的性能改进.