java判断一个时间段是否与另外几个时间段重合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
可以使用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;
            }
        }
    }
}
```

  

posted @   今年我十八岁  阅读(1490)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示