在多个日期中查找到给定日期的最近日期 [英] Find nearest date among several dates to a given date
本文介绍了在多个日期中查找到给定日期的最近日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个日期列表和一个当前日期.如何找到最接近当前日期的日期?
I have a list of dates and a current date. How can I find the date which is nearest to the current date?
推荐答案
I'd use Collection.min
with a custom comparator that "orders" the dates according to distance from current time.
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);
}
});
这篇关于在多个日期中查找到给定日期的最近日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文