1. 程式人生 > 其它 >判斷多個時間段區間是否有重疊

判斷多個時間段區間是否有重疊

/**
* 判斷日期範圍是否有重疊(日期到天)
* @param list
* @return
*/
public static boolean overlapping(List<String> list) {
if (list == null || list.size() <= 1) {
return false;
}
for (int i = 0; i < list.size(); i++) {
String dateRange [] = list.get(i).split(" ");
Date startDate = stringToDate(dateRange[0],"yyyy-MM-dd");
Date endDate = stringToDate(dateRange[1], "yyyy-MM-dd");
for (int j = i + 1; j < list.size(); j++) {
String dateRangeJ [] = list.get(j).split(" ");
Date startDateJ = stringToDate(dateRangeJ[0],"yyyy-MM-dd");
Date endDateJ = stringToDate(dateRangeJ[1], "yyyy-MM-dd");

if (!startDateJ.before(startDate)) {
if (!startDateJ.after(endDate)) {
return true;
}
} else if (!endDateJ.before(startDate)) {
return true;
}
}
}
return false;
}

返回true表示有重疊 false表示無重疊

呼叫示例:
List<String> dateRanges = new ArrayList<>();
dateRanges.add("2021-10-01 2021-10-03");
dateRanges.add("2021-10-04 2021-10-05");
dateRanges.add("2021-10-05 2021-10-06");

overlapping(dateRanges);