两段时间交集情况分析
如图所示,四种情形,实际上可合并为判断条件:startDateFormRange1 <= endDateFromRange2 && endDateFromRange1 >= startDateFromRange2
代码实现
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.lang3.tuple.Pair;
/**
* @author lixstudy on 2021/02/23
*/
public class DateUtil {
public static final String COMMON_DATE_FORMAT = "yyyy-MM-dd";
public static final String COMMON_DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
/**
* 判断两个时间段是否存在交集,存在则为true, 不存在为false
* @param range1 left为起始时间,right为结束时间
* @param range2 left为起始时间,right为结束时间
* @return
*/
public static boolean isIntersection(Pair<Date, Date> range1, Pair<Date, Date> range2){
if (range1 == null || range2 == null){
return false;
}
Date startDateFormRange1 = range1.getLeft();
Date endDateFromRange1 = range1.getRight();
Date startDateFormRange2 = range2.getLeft();
Date endDateFromRange2 = range2.getRight();
if (startDateFormRange1 == null || endDateFromRange1 == null || startDateFormRange2 == null || endDateFromRange2 == null) {
return false;
}
eturn beforeAndEqual(startDateFormRange1, endDateFromRange2) && afterAndEqual(endDateFromRange1, startDateFormRange2);
}
/**
* 当发起比较者晚于或等于被比较者返回true, 否则返回false
* @param comparator 发起比较者
* @param compared 被比较者
* @return
*/
public static boolean afterAndEqual(Date comparator, Date compared){
return !comparator.before(compared);
}
/**
* 当发起比较者早于或等于被比较者返回true, 否则返回false
* @param comparator 发起比较者
* @param compared 被比较者
* @return
*/
public static boolean beforeAndEqual(Date comparator, Date compared){
return !comparator.after(compared);
}
// 测试代码
public static void main(String[] args) throws ParseException {
String startDaste = "2021-01-26";
String endDates = "2021-01-28";
String expireSstartDate = "2021-01-22";
String exporeEsndDate = "2021-01-25";
Date startDate = DateUtil.str2Date(startDaste);
Date endDate = DateUtil.str2Date(endDates);
Date expireStartDate = DateUtil.str2Date(expireSstartDate);
Date expireEndDate = DateUtil.str2Date(exporeEsndDate);
System.out.println(isIntersection(Pair.of(startDate, endDate), Pair.of(expireStartDate, expireEndDate)));
}
public static Date str2Date(String dateStr){
if (StringUtils.isBlank(dateStr)) {
return null;
}
SimpleDateFormat simpleDateFormat = (SimpleDateFormat)SimpleDateFormat.getDateInstance();
simpleDateFormat.applyPattern(COMMON_DATE_FORMAT);
try {
return simpleDateFormat.parse(dateStr);
} catch (ParseException e) {
throw new RuntimeException("解析日期出错");
}
}
}