在 Java 中,可以使用 LocalDateTime
、LocalDate
或 LocalTime
类来表示时间,可以使用这些类的方法来比较时间的大小关系。下面以 LocalDateTime
为例介绍如何判断两个时间区间的关系。
假设有两个时间区间:区间 A 的开始时间为 startA
,结束时间为 endA
,区间 B 的开始时间为 startB
,结束时间为 endB
。
- 区间 A 在区间 B 前面:
endA.isBefore(startB)
- 区间 A 在区间 B 后面:
startA.isAfter(endB)
- 区间 A 包含区间 B:
startA.isBefore(startB) && endA.isAfter(endB)
- 区间 A 被区间 B 包含:
startB.isBefore(startA) && endB.isAfter(endA)
- 区间 A 与区间 B 有重叠部分:
!(endA.isBefore(startB) || startA.isAfter(endB))
参考代码如下:
import java.time.LocalDateTime;
public class TimeRelation {
public static void main(String[] args) {
LocalDateTime startA = LocalDateTime.of(2021, 7, 1, 8, 0);
LocalDateTime endA = LocalDateTime.of(2021, 7, 1, 12, 0);
LocalDateTime startB = LocalDateTime.of(2021, 7, 1, 10, 0);
LocalDateTime endB = LocalDateTime.of(2021, 7, 1, 14, 0);
// 判断区间 A 和区间 B 的关系
if (endA.isBefore(startB)) {
System.out.println("区间 A 在区间 B 前面");
} else if (startA.isAfter(endB)) {
System.out.println("区间 A 在区间 B 后面");
} else if (startA.isBefore(startB) && endA.isAfter(endB)) {
System.out.println("区间 A 包含区间 B");
} else if (startB.isBefore(startA) && endB.isAfter(endA)) {
System.out.println("区间 A 被区间 B 包含");
} else {
System.out.println("区间 A 与区间 B 有重叠部分");
}
}
}