java获取两个日期之间的所有日期(年月日)

    /**
     *  获取两个日期之间的所有日期 (年月日)
     *  
     * @param startTime
     * @param endTime
     * @return
     */
    public static List<String> getBetweenDate(String startTime, String endTime){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 声明保存日期集合
        List<String> list = new ArrayList<String>();
        try {
            // 转化成日期类型
            Date startDate = sdf.parse(startTime);
            Date endDate = sdf.parse(endTime);
 
            //用Calendar 进行日期比较判断
            Calendar calendar = Calendar.getInstance();
            while (startDate.getTime()<=endDate.getTime()){
                // 把日期添加到集合
                list.add(sdf.format(startDate));
                // 设置日期
                calendar.setTime(startDate);
                //把日期增加一天
                calendar.add(Calendar.DATE, 1);
                // 获取增加后的日期
                startDate=calendar.getTime();
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return list;
    }
 
    public static void main(String[] args) throws ParseException {
        String startStr = "2022-02-26";
        String endStr = "2022-03-09";
        List<String> list = getBetweenDate(startStr, endStr);
        System.out.println(list);
    }

[2022-02-26, 2022-02-27, 2022-02-28, 2022-03-01, 2022-03-02, 2022-03-03, 2022-03-04, 2022-03-05, 2022-03-06, 2022-03-07, 2022-03-08, 2022-03-09]

posted @ 2022-06-15 10:10  图图小淘气_real  阅读(1428)  评论(0编辑  收藏  举报