0
点赞
收藏
分享

微信扫一扫

java 找出两个日期区间的重合部分

今天正打算摸鱼的时候,结果来了个需求 说给两个日期区间,然后要找到两个区间的公共部分时间区间,还得计算公共部分的天数.

输入:"2023-07-01", "2023-09-01", "2023-06-01", "2023-07-21" 输出: 开始日期 -> "2023-07-01", 结束日期 -> "2023-07-21", 相隔天数 -> 21 具体实现

public static Map<String, Object> coincideDate(String start, String end, String rangStart, String rangEnd) {
        Map<String, Object> resultMap = new HashMap<>();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd", Locale.CHINA);
        LocalDate startDate = LocalDate.parse(start, dateTimeFormatter);
        LocalDate endDate = LocalDate.parse(end, dateTimeFormatter);
        LocalDate rangStartDate = LocalDate.parse(rangStart, dateTimeFormatter);
        LocalDate rangEndDate = LocalDate.parse(rangEnd, dateTimeFormatter);
        if (startDate.isAfter(endDate) || rangStartDate.isAfter(rangEndDate)) {
            return resultMap;
        }
        if (startDate.isBefore(rangStartDate)) {
            if (endDate.isBefore(rangStartDate)) {
                return resultMap;
            }
        } else {
            if (startDate.isAfter(rangEndDate)) {
                return resultMap;
            }
        }
        LocalDate startLocalDate = startDate.isBefore(rangStartDate) ? rangStartDate : startDate;
        LocalDate endLocalDate = endDate.isAfter(rangEndDate) ? rangEndDate : endDate;
        String startStr = startLocalDate.format(dateTimeFormatter);
        String endStr = endLocalDate.format(dateTimeFormatter);
        //返回开始、结束时间和间隔天数
        resultMap.put("startStr", startStr);
        resultMap.put("endStr", endStr);
        long daysBetween = ChronoUnit.DAYS.between(startLocalDate, endLocalDate) + 1L;
        resultMap.put("days", Convert.toInt(daysBetween));
        return resultMap;
    }

返回一个map结果 image.png

举报

相关推荐

0 条评论