本文介绍了从列表中查找最近的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个日期列表和当前日期。
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);
}
});
这篇关于从列表中查找最近的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!