java 在给定日期的多个日期中查找最近的日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3884644/
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
Find nearest date among several dates to a given date
提问by salman raza
I have a list of dates and a current date. How can I find the date which is nearest to the current date?
我有一个日期列表和一个当前日期。如何找到最接近当前日期的日期?
回答by aioobe
I'd use Collection.min
with a custom comparator that "orders" the dates according to distance from current time.
我将Collection.min
与自定义比较器一起使用,该比较器根据与当前时间的距离“订购”日期。
final long now = System.currentTimeMillis();
// Create a sample list of dates
List<Date> dates = new ArrayList<Date>();
Random r = new Random();
for (int i = 0; i < 10; i++)
dates.add(new Date(now + r.nextInt(10000)-5000));
// Get date closest to "now"
Date closest = Collections.min(dates, new Comparator<Date>() {
public int compare(Date d1, Date d2) {
long diff1 = Math.abs(d1.getTime() - now);
long diff2 = Math.abs(d2.getTime() - now);
return Long.compare(diff1, diff2);
}
});
回答by Michael Borgwardt
If the list is sorted, then you can use Collections.binarySearch()
to find the place where the given date would be sorted into the list - the closest one is either right after or right before that index.
如果列表已排序,那么您可以使用Collections.binarySearch()
来查找给定日期将在列表中排序的位置 - 最接近的位置在该索引之后或之前。
For very large lists, this is much faster than the other solutions, but of course it does require the list to be sorted. If you're going to do such a query multiple times, it would be worth it (performance-wise) to sort the list first.
对于非常大的列表,这比其他解决方案快得多,但当然它确实需要对列表进行排序。如果您要多次执行这样的查询,那么首先对列表进行排序是值得的(性能方面)。
回答by Steve Kuo
If you can use a Set
instead of a List
, put the dates in a NavigableSet
such as TreeSet
and use the methods lower
and higher
.
如果您可以使用 aSet
代替 a List
,请将日期放入NavigableSet
例如TreeSet
并使用方法lower
和higher
。
NavigableSet<Date> dates = new TreeSet<Date>();
// add some dates to dates
Date now = new Date();
Date highestDateUpUntilNow = dates.lower(now);
回答by MStodd
Loop through all dates with the following:
1. Have a variable that keeps track of the current closest date
2. Have a variable that is the difference between the current closest date and the current date
使用以下内容循环所有日期:
1. 有一个跟踪当前最近日期
的变量 2. 有一个变量是当前最近日期和当前日期之间的差异
When you find a date with a difference less than that of the what you're keeping track of in (2), update the difference and the current closest date
当您发现一个日期的差异小于您在 (2) 中跟踪的日期时,更新差异和当前最接近的日期
At the end, the current closest date is the closest date in the collection
最后,当前最近的日期是集合中最近的日期
here's code in python:
这是python中的代码:
dates = [date(2010,1,2), date(2010,5,6), date(2010,3,4), date(2011, 1, 2), date(2010,10,20), date(2009,2,3)]
current_date = dates[0]
current_min = abs(current_date - date.today())
for d in dates:
if abs(d - date.today()) < current_min:
current_min = abs(d - date.today())
current_date = d
回答by Colin Hebert
You can try this code :
你可以试试这个代码:
public static Date closerDate(Date originalDate, Collection<Date> unsortedDates) {
List<Date> dateList = new LinkedList<Date>(unsortedDates);
Collections.sort(dateList);
Iterator<Date> iterator = dateList.iterator();
Date previousDate = null;
while (iterator.hasNext()) {
Date nextDate = iterator.next();
if (nextDate.before(originalDate)) {
previousDate = nextDate;
continue;
} else if (nextDate.after(originalDate)) {
if (previousDate == null || isCloserToNextDate(originalDate, previousDate, nextDate)) {
return nextDate;
}
} else {
return nextDate;
}
}
return previousDate;
}
private static boolean isCloserToNextDate(Date originalDate, Date previousDate, Date nextDate) {
if(previousDate.after(nextDate))
throw new IllegalArgumentException("previousDate > nextDate");
return ((nextDate.getTime() - previousDate.getTime()) / 2 + previousDate.getTime() <= originalDate.getTime());
}