美文网首页
java获取一段时间的每一天

java获取一段时间的每一天

作者: 惜鸟 | 来源:发表于2020-03-11 18:06 被阅读0次

一、概述

在写java代码过程遇到一个场景,给定开始和结束日期需要判断这段时间的哪一天在数据库中不存在,所以需要获取这段时间的每一天,查阅了网上的资料这里做一个总结,方便自己理解也希望能帮助到其他同学。

二、代码实现如下

1、java8之前的实现方式

    public static void main(String[] args) {
        System.out.println(findDates("2020-02-02", "2020-03-03"));
    }

    public static List<String> findDates(String startTime, String endTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<String> dateList = new ArrayList<>();
        try {
            // 使用SimpleDateFormat将字符串转换为Date
            Date startDate = sdf.parse(startTime);
            // 使用SimpleDateFormat将字符串转换为Date
            Date endDate = sdf.parse(endTime);
            // 获取Calendar的实例
            Calendar startCal = Calendar.getInstance();
            // 将开始的Date设置到Calendar中
            startCal.setTime(startDate);
            // 将开始时间添加到列表中
            dateList.add(startTime);
            // 判断如果endDate在startDate之后则为true
            while (endDate.after(startCal.getTime())) {
                // 在当前时间的基础上加一天
                startCal.add(Calendar.DAY_OF_MONTH, 1);
                // 添加到列表中
                dateList.add(sdf.format(startCal.getTime()));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return dateList;
    }

二、使用java8的LocalDate实现

    public static void main(String[] args) {
        System.out.println(getBetweenDate("2020-02-02", "2020-03-03"));
    }

    public static List<String> getBetweenDate(String start, String end) {
        List<String> list = new ArrayList<>();
        // LocalDate默认的时间格式为2020-02-02
        LocalDate startDate = LocalDate.parse(start);
        LocalDate endDate = LocalDate.parse(end);
        long distance = ChronoUnit.DAYS.between(startDate, endDate);
        if (distance < 1) {
            return list;
        }
        Stream.iterate(startDate, d -> d.plusDays(1)).limit(distance + 1).forEach(f -> list.add(f.toString()));
        return list;
    }

相关文章

网友评论

      本文标题:java获取一段时间的每一天

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