以上代码优化下,需要传入4个参数,第一个时间段的开始时间,第一个时间段的结束时间,要检查的时间段的开始时间,要检查的时间段的结束时间,java17实现,考虑跨夜
时间: 2023-09-13 15:03:08 浏览: 49
可以使用Java 17中的`java.time`包来实现该功能。以下是优化后的代码示例,它可以接受四个参数,并检查第三个参数表示的时间段是否与第一个参数表示的时间段重叠:
```java
import java.time.Duration;
import java.time.LocalDateTime;
public class TimeOverlapChecker {
public static boolean isOverlap(LocalDateTime start1, LocalDateTime end1, LocalDateTime start2, LocalDateTime end2) {
// 如果开始时间或结束时间为空,则不重叠
if (start1 == null || end1 == null || start2 == null || end2 == null) {
return false;
}
// 计算第一个时间段的持续时间
Duration duration1 = Duration.between(start1, end1);
// 如果持续时间为0,则不重叠
if (duration1.isZero() || duration1.isNegative()) {
return false;
}
// 计算第二个时间段的持续时间
Duration duration2 = Duration.between(start2, end2);
// 如果持续时间为0,则不重叠
if (duration2.isZero() || duration2.isNegative()) {
return false;
}
// 计算两个时间段的开始时间和结束时间的最大值和最小值
LocalDateTime earliestStart = start1.isBefore(start2) ? start1 : start2;
LocalDateTime latestEnd = end1.isAfter(end2) ? end1 : end2;
// 计算最大持续时间
Duration maxDuration = Duration.between(earliestStart, latestEnd);
// 如果最大持续时间小于等于两个持续时间之和,则重叠
return maxDuration.compareTo(duration1.plus(duration2)) >= 0;
}
}
```
在上述代码中,我们首先计算了两个时间段的持续时间,并检查它们是否为零或负。如果持续时间为零或负,则意味着时间段无效,因此不可能重叠。接下来,我们计算了两个时间段的开始时间和结束时间的最大值和最小值,并计算了最大持续时间。最后,我们将最大持续时间与两个持续时间之和进行比较,以确定时间段是否重叠。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)