验证时间段区间是否有交叉/重叠

发布时间:2023-12-21 13:45:11

点赞再看,养成习惯,大家好,我是辰兮!今天介绍如何验证时间段区间是否有交叉/重叠

文章目录:

前言

一、引入库

二、使用步骤

总结


前言

在日常开发过程中,经常会有导入需要校验时间段区间是否有交叉/重叠,所以为此在此记录一下。

一、引入库

本文用到了一个maven包:
?

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>31.1-jre</version>
</dependency>

二、使用步骤

代码如下(示例):

Map<String, List<ProductionPlanTemplate>> voGroup = productionPlanTemplates.stream()
                .collect(Collectors.groupingBy(p -> p.getProductionNodeCode() + p.getProductCode()));
        List<String> overlappingTimeIds = voGroup.entrySet().stream().filter(v -> {
            List<LocalDateTime> dates = v.getValue().stream()
                    .sorted(comparing(m -> DateUtils.toLocalDateTime(m.getScheduleDateStart(), m.getStartTime())))
                    .flatMap(m -> localDateTimeStream(m.getScheduleDateStart(), m.getStartTime(), m.getScheduleDateEnd(), m.getEndTime())).collect(toList());
            return !Ordering.usingToString().isOrdered(dates);
        }).map(Map.Entry::getKey).collect(toList());


private Stream<LocalDateTime> localDateTimeStream(String startupDate, String startTime, String endUpDate, String endTime) {
        LocalDate start = DateUtils.toLocalDate(startupDate);
        LocalDate end = DateUtils.toLocalDate(endUpDate);
        LocalTime startTimeLocal = LocalTime.parse(startTime);
        LocalTime endTimeLocal = LocalTime.parse(endTime);
        LocalDateTime startDateTime = LocalDateTime.of(start, startTimeLocal);
        LocalDateTime endDateTime = LocalDateTime.of(end, endTimeLocal);
        return Stream.of(startDateTime, endDateTime);
    }

总结

1、首先我们通过逻辑去对productionPlanTemplates进行分组,对每一组去校验是否有重叠时间

2、然后我们通过startDate('yyyy-MM-dd')以及startTime(HH:mm:ss)进行排序

3、接着,将这些对象的开始日期时间和结束日期时间转为LocalDateTime对象,并将这些对象收集到一个列表中。

4、使用Guava库的Ordering类判断是否是有序,通过filter操作进行筛选

5、最终将每一组有时间段区间交叉/重叠的Key值收集到一个列表里面。

文章来源:https://blog.csdn.net/ke2602060221/article/details/135102380
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。