我希望知道如何输入一个方法来给我最接近指定日期的日期。我的意思是以下内容:
public Date getNearestDate(List<Date> dates, Date currentDate) {
return closestDate // The date that is the closest to the currentDate;
}
我发现了类似的问题,但只有一个有很好的答案,而且代码一直给我 NullPointerExceptions ... 谁能帮助我?
您可以通过计算时间差(例如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;
}
[编辑]
较小的性能改进。
使用Date#getTime并减去这些值。最小的结果将是您最近的日期。
按日期顺序对列表进行排序并执行二分搜索。请记住,要比较日期,您可以使用 Date.getTime() 以毫秒为单位获取日期,这通常更容易比较。
您将按最接近的日期排序。
将开始日期设置为 0:
long ret = 0;
现在您需要遍历您的列表并保持最接近您想要的日期
for(Date d : dates){
if(Math.abs(curDate.getTime() - ret) > Math.abs(curDate.getTime() - d.getTime())){
ret = d.getTime();
}
}
return new Date(ret);
该if
语句通过比较毫秒时间来检查哪个日期更接近。通过使用 Math.abs,您可以消除方向(之前或之后)。