判断两个LocalDateTime时间段是否重叠的条件是:startA.isBefore(endB) && startB.isBefore(endA);端点相接默认不重叠,若需包含则改用!startA.isAfter(endB) && !startB.isAfter(endA)。

判断两个 LocalDateTime 时间段是否重叠,核心是逻辑判断:只要不满足“完全分离”,就视为重叠。
重叠的判定条件
设时间段 A 为 [startA, endA],时间段 B 为 [startB, endB],且所有时间均为有效(即 start ≤ end):
- 不重叠的唯一情况是:A 完全在 B 左边(endA < startB)或 A 完全在 B 右边(endB < startA)
- 因此,重叠的条件就是:! (endA.isBefore(startB) || endB.isBefore(startA))
- 等价写法(更直观):startA.isBefore(endB) && startB.isBefore(endA)
推荐实现方式(简洁可靠)
直接使用 isBefore 判断,无需取反或额外校验(前提是输入时间段本身合法):
public static boolean isOverlap(LocalDateTime startA, LocalDateTime endA,
LocalDateTime startB, LocalDateTime endB) {
return startA.isBefore(endB) && startB.isBefore(endA);
}
✅ 示例验证:
立即学习“Java免费学习笔记(深入)”;
- A: [2026-07-10T09:00, 2026-07-10T11:00]
- B: [2026-07-10T10:30, 2026-07-10T12:00]
-
startA.isBefore(endB)→ 09:00 < 12:00 → true -
startB.isBefore(endA)→ 10:30 < 11:00 → true - 返回 true(正确识别重叠)
封装成对象方法更易复用
定义一个不可变的时间段类,把逻辑内聚:
public final class TimeSlot {
private final LocalDateTime start;
private final LocalDateTime end;
public TimeSlot(LocalDateTime start, LocalDateTime end) {
if (start.isAfter(end)) {
throw new IllegalArgumentException("start must not be after end");
}
this.start = start;
this.end = end;
}
public boolean overlaps(TimeSlot other) {
return this.start.isBefore(other.end) && other.start.isBefore(this.end);
}
}
调用示例:
TimeSlot a = new TimeSlot(LocalDateTime.of(2026, 7, 10, 9, 0),
LocalDateTime.of(2026, 7, 10, 11, 0));
TimeSlot b = new TimeSlot(LocalDateTime.of(2026, 7, 10, 10, 30),
LocalDateTime.of(2026, 7, 10, 12, 0));
System.out.println(a.overlaps(b)); // true
注意边界情况
默认情况下,端点相接不算重叠(例如 A 结束于 10:00,B 开始于 10:00):
-
[08:00–10:00]和[10:00–12:00]→isBefore返回 false → 不重叠 - 如需包含“端点接触即重叠”,改用
!startA.isAfter(endB) && !startB.isAfter(endA) - 即把
isBefore换成!isAfter,允许等于关系


















