1 需求
有一个List ,现在有一个Date 时间,找到这个list 里面和时间最近的一个,进行返回
2 实现
代码语言:javascript复制public static Date findNearestDate(List<Date> dateList, Date targetDate) {
Date nearestDate = null;
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (Date date : dateList) {
long diff = Math.abs(targetDate.getTime() - date.getTime());
if (nearestDate == null || diff < Math.abs(nearestDate.getTime() - targetDate.getTime())) {
nearestDate = date;
}
}
return nearestDate;
}