Java 输入两个时间日期,输出每个自然月的起始和结束时间日期

上代码: 

public static List<CycleTimeVo> getMonthBetween(String minDate, String maxDate) throws Exception {
        //  ArrayList<String> result = new ArrayList<String>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//格式化为年月

        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();

        min.setTime(sdf.parse(minDate));
        min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

        max.setTime(sdf.parse(maxDate));
        max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

        Calendar curr = min;

        List<CycleTimeVo> CycleTimeList=new ArrayList();
        while (curr.before(max)) {

            CycleTimeVo cycleTimeVo=new CycleTimeVo();
            cycleTimeVo.setStartTimeStr(sdf.format(curr.getTime()));
            String monthEnd = getMonthEnd(sdf.format(curr.getTime()));
            cycleTimeVo.setEndTimeStr(monthEnd);
            CycleTimeList.add(cycleTimeVo);
            //result.add(sdf.format(curr.getTime()));
            curr.add(Calendar.MONTH, 1);
        }

        return CycleTimeList;
    }


    public static String getMonthEnd(String  time) throws ParseException {
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        Date date= simpleDateFormat.parse(time);
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        //设置为当月最后一天
        c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
        //将小时至23
        c.set(Calendar.HOUR_OF_DAY, 23);
        //将分钟至59
        c.set(Calendar.MINUTE, 59);
        //将秒至59
        c.set(Calendar.SECOND,59);
        //将毫秒至999
        c.set(Calendar.MILLISECOND, 999);
        // 获取本月最后一天的时间
        return simpleDateFormat.format(c.getTime());
    }

测试结果:

        List<CycleTimeVo> monthBetween = getMonthBetween("2019-01-01", "2020-06-03");


        System.out.println(monthBetween);

可以看到每个月的开始日期可结束日期都获取到了: 

PS: 如果是要算出两个日期之间的月数,则只需要对最后的list取其size 即可。

发布了181 篇原创文章 · 获赞 289 · 访问量 27万+

猜你喜欢

转载自blog.csdn.net/qq_35387940/article/details/104357775
今日推荐