一个List时间集合,一个日期。在集合中返回离该日期最近的一个时间

一个List时间集合,一个日期。在集合中返回离该日期最近的一个时间

/**
* 找出匹配时间(标准时间,时间列表)
*
* @param equMonitoringStandardDate
* 标准时间
* @param pipeMonitoringDates
* 时间列表
* @return
/
public static Date getMatchTime(Date equMonitoringStandardDate, List pipeMonitoringDates) {
// 在时间列表中找出匹配的时间
/
*
* 标准时间在正负(匹配间隔时间)内最近的时间 注意:先找负,找不到再找正
*/
// 数据匹配间隔时间(分钟)
//String value = StaticSysMacroService.get(Constant.GDSBPPSJ).getValue();
String value = “5”;
int intervalTime = Integer.parseInt(value);// 分钟
// 标准时间+?分钟(取集合正时间内的date)
Date loseDate = new Date(equMonitoringStandardDate.getTime() - intervalTime * 60 * 1000);
// 标准时间+?分钟(取集合负时间内的date)
Date justDate = new Date(equMonitoringStandardDate.getTime() + intervalTime * 60 * 1000);
// 负时间的list
List loseDateList = new ArrayList<>();
for (Date date : pipeMonitoringDates) {
//过滤掉正的
if(date.getTime()<=equMonitoringStandardDate.getTime()){
//在时间范围内就加入负的集合
if(date.getTime()>=loseDate.getTime()){
loseDateList.add(date);
}
}
}
// 正时间的list
List justDateList = new ArrayList<>();
for (Date date : pipeMonitoringDates) {
//过滤掉负的
if(date.getTime()>=equMonitoringStandardDate.getTime()){
//在时间范围内就加入正的集合
if(date.getTime()<=justDate.getTime()){
justDateList.add(date);
}
}
}
//最近的时间
Date recentTime=new Date();
//先找负的
if(loseDateList.size()>0){
//如果复合的只有一条直接返回匹配时间
if(loseDateList.size()==1){
return loseDateList.get(0);
//否则
}else{
long minDiff=equMonitoringStandardDate.getTime()-loseDateList.get(0).getTime();
for (int i = 0; i < loseDateList.size(); i++) {
long diff =equMonitoringStandardDate.getTime()-loseDateList.get(i).getTime();
diff = Math.abs(diff);
if(minDiff>diff){
recentTime=loseDateList.get(i);
}else{
recentTime=loseDateList.get(0);
}
}
return recentTime;
}
}
//再找正的
if(justDateList.size()>0){
//如果复合的只有一条直接返回匹配时间
if(justDateList.size()==1){
return justDateList.get(0);
//否则
}else{
long minDiff=justDateList.get(0).getTime()-equMonitoringStandardDate.getTime();
for (int i = 0; i < justDateList.size(); i++) {
long diff =justDateList.get(0).getTime()-equMonitoringStandardDate.getTime();
diff = Math.abs(diff);
if(minDiff>diff){
recentTime=justDateList.get(i);
}else{
recentTime=justDateList.get(0);
}
}
return recentTime;
}
}
return null;
}

一个List时间集合,一个日期。在集合中返回离该日期最近的一个时间
根据我项目的需求,我加了一些业务逻辑。如果您需要,只做一下稍微的改动就能实现原有的功能了。