最近和同事聊天,提到了他要在整一个判断多个时间段中,是否有重叠时间的工具类,回去想了想参考了其余大佬的,经过反复测验,把方法分享出来,当然也有大佬提出可以用DateUtils.compare解决的,方法多种多样的。
思路:
1.比较时间段A1-A2和B1-B2,可以是B1或B2在A1-A2之间,用Date的befor和after即可。
2.两层for循环实现,同时要求A不能和本身比较,A要和自己之前或之后的时间段进行比较,即先进行排序用
Collections.sort(list)方法,防止重复比较。
代码:
package test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @Author: xs
* @Description: 判断多个时间段中,是否重叠的时间
* @Date:Create:in 2020/6/28 10:52
* @Modified By:
*/
public class test1 {
public static void testChongDie(List<String> list){
//先把所有时间进行排序
Collections.sort(list);
//排序之后输入
System.out.println(list.toString());
SimpleDateFormat formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
try {
for(int i =0;i<list.size();i++){
String[] date1 = list.get(i).split("--");
Date startdate1 = formater.parse(date1[0]);
Date enddate1 = formater.parse(date1[1]);
// 不让自己和自己进行比较,j从i的下一个开始
for (int j =i+1;j<list.size();j++){
String[] date2 = list.get(j).split("--");
Date startdate2 = formater.parse(date2[0]);
Date enddate2 = formater.parse(date2[1]);
if(startdate1.before(startdate2) && enddate1.after(startdate2)){
System.out.println(list.get(i)+"与"+list.get(j)+"有重叠");
}
}
}
} catch (ParseException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("2011/12/13 10:52:12--2013/12/20 20:52:12");
list.add("2011/12/10 08:52:12--2011/12/12 12:23:12");
list.add("2011/12/26 06:52:12--2011/12/30 08:52:12");
list.add("2011/11/14 13:52:12--2012/2/25 08:52:12");
list.add("2011/12/24 02:52:12--2011/12/18 08:52:12");
testChongDie(list);
}
}
输出结果:
排序后的时间段:
[2011/11/14 13:52:12--2012/2/25 08:52:12,
2011/12/10 08:52:12--2011/12/12 12:23:12,
2011/12/13 10:52:12--2013/12/20 20:52:12,
2011/12/24 02:52:12--2011/12/18 08:52:12,
2011/12/26 06:52:12--2011/12/30 08:52:12]
2011/11/14 13:52:12--2012/2/25 08:52:12与2011/12/10 08:52:12--2011/12/12 12:23:12有重叠
2011/11/14 13:52:12--2012/2/25 08:52:12与2011/12/13 10:52:12--2013/12/20 20:52:12有重叠
2011/11/14 13:52:12--2012/2/25 08:52:12与2011/12/24 02:52:12--2011/12/18 08:52:12有重叠
2011/11/14 13:52:12--2012/2/25 08:52:12与2011/12/26 06:52:12--2011/12/30 08:52:12有重叠
2011/12/13 10:52:12--2013/12/20 20:52:12与2011/12/24 02:52:12--2011/12/18 08:52:12有重叠
2011/12/13 10:52:12--2013/12/20 20:52:12与2011/12/26 06:52:12--2011/12/30 08:52:12有重叠