java判断一个时间段是否与另外几个时间段重合
可以使用Java中的DateTime API来判断时间段是否重合。具体实现可以参考以下步骤: 1. 创建需要判断是否重合的时间段对象和已有时间段的对象列表。 ```java // 创建需要判断是否重合的时间段对象 LocalDateTime start1 = LocalDateTime.of(2021, 1, 1, 9, 0); LocalDateTime end1 = LocalDateTime.of(2021, 1, 1, 10, 0); Duration duration1 = Duration.between(start1, end1); // 创建已有的时间段对象列表 List<Duration> durations = new ArrayList<>(); LocalDateTime start2 = LocalDateTime.of(2021, 1, 1, 8, 30); LocalDateTime end2 = LocalDateTime.of(2021, 1, 1, 9, 30); Duration duration2 = Duration.between(start2, end2); durations.add(duration2); LocalDateTime start3 = LocalDateTime.of(2021, 1, 1, 10, 0); LocalDateTime end3 = LocalDateTime.of(2021, 1, 1, 11, 0); Duration duration3 = Duration.between(start3, end3); durations.add(duration3); ``` 2. 遍历已有时间段列表,使用overlaps()方法判断需要判断的时间段是否重合。 ```java for (Duration duration : durations) { if (duration1.overlaps(duration)) { System.out.println("时间段重合"); break; } } ``` 完整代码示例: ```java import java.time.Duration; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { // 创建需要判断是否重合的时间段对象 LocalDateTime start1 = LocalDateTime.of(2021, 1, 1, 9, 0); LocalDateTime end1 = LocalDateTime.of(2021, 1, 1, 10, 0); Duration duration1 = Duration.between(start1, end1); // 创建已有的时间段对象列表 List<Duration> durations = new ArrayList<>(); LocalDateTime start2 = LocalDateTime.of(2021, 1, 1, 8, 30); LocalDateTime end2 = LocalDateTime.of(2021, 1, 1, 9, 30); Duration duration2 = Duration.between(start2, end2); durations.add(duration2); LocalDateTime start3 = LocalDateTime.of(2021, 1, 1, 10, 0); LocalDateTime end3 = LocalDateTime.of(2021, 1, 1, 11, 0); Duration duration3 = Duration.between(start3, end3); durations.add(duration3); // 遍历已有时间段列表,判断时间段是否重合 for (Duration duration : durations) { if (duration1.overlaps(duration)) { System.out.println("时间段重合"); break; } } } } ```