JAVA 获取某段时间内的所有日期集合

集合里包含月份: 开始~结束
2019-01-01 00:00:00
2019-01-31 23:59:00
2019-02-01 00:00:00
2019-02-28 23:59:00
2019-03-01 00:00:00
2019-03-31 23:59:00

    public static void main(String[] args) throws ParseException {
        long l = System.currentTimeMillis();//当前时间戳
        String nowDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(l));//当前时间字符串
        String startDate ="2019-01-01 00:00:00";
        List<String> dates = findMonths(startDate, nowDate);
        for (int i = 0; i < dates.size(); i++) {
            System.out.println(dates.get(i));
        }

    }

    /**
     * 获取对应日期列表
     * @param dBegin
     * @param dEnd
     * @return
     * @throws ParseException
     * @throws java.text.ParseException
     */
    public static List<String> findMonths(String dBegin, String dEnd) throws ParseException, java.text.ParseException {
        //日期工具类准备
        DateFormat resulfmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //设置开始时间
        Calendar calBegin = Calendar.getInstance();
        calBegin.setTime(resulfmt.parse(dBegin));
        //设置结束时间
        Calendar calEnd = Calendar.getInstance();
        calEnd.setTime(resulfmt.parse(dEnd));
        //装返回的日期集合容器
        List<String> dateList = new ArrayList<String>();
        // 每次循环给calBegin日期加一天,直到calBegin.getTime()时间等于dEnd
        while (calEnd.after(calBegin))  {
            // 根据日历的规则,为给定的日历字段添加或减去指定的时间量
                // 优先记录当月时间: 开始时间
            dateList.add(resulfmt.format(calBegin.getTime()));
                // 优先记录当月时间: 结束
                    // 当前日历月份加1 来到了下个月
            calBegin.add(Calendar.MONTH, 1);
                    // 下个月天数减1 来到了当月(即开始月份)的最后一天
            //calBegin.add(Calendar.DAY_OF_MONTH, -1);
                    // 下个月时间减1分钟 来到了当月(即开始月份)的最后一天的23:59:00
            calBegin.add(Calendar.MINUTE,-1);
                // 记录当月的结束时间  82800000L
            dateList.add(resulfmt.format(calBegin.getTime()));//获取当前日历时间戳并格式化
            // 当前月份加1得到下个月份 
            // calBegin.add(Calendar.DAY_OF_MONTH, 1);
            calBegin.add(Calendar.MINUTE, 1);
            //依次循环并记录日期
        }
        return dateList;
    }
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值