美文网首页
获取两个日期中间的所有天数

获取两个日期中间的所有天数

作者: AC编程 | 来源:发表于2022-10-21 10:25 被阅读0次

一、代码

public class LocalDateTimeUtil {

    public LocalDateTimeUtil() {
        throw new RuntimeException("工具类,不用创建");
    }

    /**
     * 获取两个日期中间的所有天数
     *
     * @return
     */
    public static List<LocalDateTime> listBetweenDate(String startDayStr, String endDayStr) {
        String[] startArray = startDayStr.split(" ");
        String[] endArray = endDayStr.split(" ");

        String start = startArray[0];
        String startTime = startArray[1];

        String end = endArray[0];
        String endTime = endArray[1];

        if (startTime.equals(endTime)) {
            //如果时间相同,则不用拆开处理了,
            LocalDateTime startDay = LocalDateTime.parse(startDayStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            LocalDateTime endDay = LocalDateTime.parse(endDayStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            return listBetweenDate(startDay, endDay);
        } else {
            //"2022-11-04 19:30:00", "2022-11-05 16:30:00"  需要拆开比较,不然只会返回一天,出现BUG
            LocalDateTime startDay = LocalDateTime.parse(start + " 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            LocalDateTime endDay = LocalDateTime.parse(end + " 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

            List<LocalDateTime> dayTimeList = listBetweenDate(startDay, endDay);
            List<LocalDateTime> newDayTimeList = new ArrayList<>();
            for (LocalDateTime item : dayTimeList) {
                LocalDateTime newDayTime = LocalDateTime.of(item.toLocalDate(), LocalTime.parse(startTime));
                newDayTimeList.add(newDayTime);
            }
            newDayTimeList.remove(dayTimeList.size() - 1);

            LocalDateTime lastDayTime = dayTimeList.get(dayTimeList.size() - 1);
            LocalDateTime lastNewDayTime = LocalDateTime.of(lastDayTime.toLocalDate(), LocalTime.parse(endTime));
            newDayTimeList.add(lastNewDayTime);

            return newDayTimeList;
        }
    }

    /**
     * 获取两个日期中间的所有天数
     *
     * @return
     */
    public static List<LocalDateTime> listBetweenDate(LocalDateTime startDay, LocalDateTime endDay) {
        List<LocalDateTime> list = new ArrayList<>();
        long distance = ChronoUnit.DAYS.between(startDay, endDay);
        Stream.iterate(startDay, d -> d.plusDays(1)).limit(distance + 1).forEach(f -> list.add(f));
        return list;
    }
}

二、测试

public class Test {

    public static void main(String[] args) {
        List<LocalDateTime> timeList = LocalDateTimeUtil.listBetweenDate("2022-11-04 19:30:00", "2022-11-05 16:30:00");
        
        //[2022-11-04T19:30, 2022-11-05T16:30]
        System.out.println(timeList);
    }
}

相关文章

网友评论

      本文标题:获取两个日期中间的所有天数

      本文链接:https://www.haomeiwen.com/subject/vkquzrtx.html