java 我将如何找到最接近指定日期的日期?(爪哇)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7128704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How would I go about finding the closest date to a specified date? (Java)
提问by Confiqure
I was hoping to know how I would type up a method to give me the closest date to a specified date. What I mean is something along the following:
我希望知道我将如何输入一种方法来为我提供最接近指定日期的日期。我的意思是以下内容:
public Date getNearestDate(List<Date> dates, Date currentDate) {
return closestDate // The date that is the closest to the currentDate;
}
I have found similar questions, but only one had a good answer and the code kept giving me NullPointerExceptions ... Can anyone help me?
我发现了类似的问题,但只有一个有一个很好的答案,并且代码一直给我 NullPointerExceptions ......有人可以帮助我吗?
回答by maerics
You can solve in linear time by computing the difference in time (e.g. Date#getTime()
) and returning the minimum:
您可以通过计算时间差(例如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;
}
[Edit]
[编辑]
Minor performance improvements.
较小的性能改进。
回答by dertkw
Use Date#getTimeand substract the values. The smallest result will be your closest date.
使用Date#getTime并减去这些值。最小的结果将是您最近的日期。
回答by SJuan76
Order the list by order of dates and perform a dichotomic search. Remember that to compare the dates you can use Date.getTime() to get the date as milliseconds, which are usually easier to compare.
按日期顺序排列列表并执行二分搜索。请记住,要比较日期,您可以使用 Date.getTime() 以毫秒为单位获取日期,这通常更容易比较。
回答by Ryan Amos
You would order the dates by the closest.
您会按最接近的日期排序。
Have a start date set to 0:
将开始日期设置为 0:
long ret = 0;
long ret = 0;
Now you need to loop though your list and keep the closest to your desired date
现在您需要遍历您的列表并保持最接近您想要的日期
for(Date d : dates){
if(Math.abs(curDate.getTime() - ret) > Math.abs(curDate.getTime() - d.getTime())){
ret = d.getTime();
}
}
return new Date(ret);
The if
statement checks which date is closer by comparing the millisecond time. By using Math.abs, you eliminate direction (before or after).
该if
语句通过比较毫秒时间来检查哪个日期更接近。通过使用 Math.abs,您可以消除方向(之前或之后)。