此方法主要是在java中判断时间段与时间段之间是否重合
判断多个时间段是否有间隔
实体类内容
public class DateRangeStr {
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM", timezone = "GMT+8")
private String startDate;//格式:yyyy-MM-dd
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM", timezone = "GMT+8")
private String endDate;//格式:yyyy-MM-dd
}
主方法内容
//判断多个时间段是否有时间间隔 true无间隔 false有间隔
public boolean hasNoGaps(List<DateRangeStr> sortedStrRanges) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
if (sortedStrRanges == null || sortedStrRanges.size() <= 0) return false;
if (sortedStrRanges.size() == 1) return true;
List<DateRange> timePeriods = new ArrayList<>();
for (DateRangeStr ss : sortedStrRanges) {
LocalDate startDate = LocalDate.parse(ss.getStartDate(), formatter);
LocalDate endDate = LocalDate.parse(ss.getEndDate(), formatter);
DateRange dr = new DateRange();
dr.setStartDate(startDate);
dr.setEndDate(endDate);
timePeriods.add(dr);
}
Collections.sort(timePeriods, Comparator.comparing(DateRange::getStartDate));
LocalDate previousEndDate = timePeriods.get(0).getEndDate();
for (int i = 1; i < timePeriods.size(); i++) {
DateRange currentPeriod = timePeriods.get(i);
if (previousEndDate.isAfter(currentPeriod.getStartDate())) {
// 当前时间段的开始日期早于上一个时间段的结束日期,存在重叠,这不一定是问题
// 但我们仍然将当前时间段的结束日期作为新的previousEndDate
previousEndDate = currentPeriod.getEndDate();
} else if ((!previousEndDate.isEqual(currentPeriod.getStartDate()) && !previousEndDate.plusDays(1L).isEqual(currentPeriod.getStartDate()))) {
// 发现了间隔
return false;
} else {
// 相邻时间段之间没有间隔
previousEndDate = currentPeriod.getEndDate();
}
}
return true; // 所有时间段都已遍历完毕,且没有发现时间间隔
}
判断时间段集合是否与某时间段重合
实体类内容
public class TimeInterval {
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM", timezone = "GMT+8")
private String start;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM", timezone = "GMT+8")
private String end;
}
主方法内容
private static YearMonth parseYearMonth(String input) {
try {
return YearMonth.parse(input, MONTH_FORMATTER);
} catch (Exception e) {
throw new IllegalArgumentException("Invalid date format: " + input, e);
}
}
public static boolean overlapsOrContainedInIntervals(List<TimeInterval> intervals, String startDate,String endDate) {
YearMonth yearMonthAStart = parseYearMonth(startDate);
YearMonth yearMonthAEnd = parseYearMonth(endDate);
for (TimeInterval interval : intervals) {
YearMonth start = parseYearMonth(interval.getStart());
YearMonth end = parseYearMonth(interval.getEnd());
// 检查重叠或包含
if (!start.isAfter(yearMonthAEnd) && !end.isBefore(yearMonthAStart)) {
return true;
}
}
return false;
}