java小工具之获取两个日期月份中的所有月份

例如:要取2019-01  到  2020-06之间的所有月份

/**获取两月之间的所有月份*/
    public static List<String> getMonthBetween(String minDate, String maxDate){
        ArrayList<String> result = new ArrayList<String>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");//格式化为年月

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

        try{
            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);
        }catch (Exception e){
            throw new SSCException("分解月份出错");//注意:抛出的类型是自定义的
        }

        Calendar curr = min;
        while (curr.before(max)) {
            result.add(sdf.format(curr.getTime()));
            curr.add(Calendar.MONTH, 1);
        }
        min = null;max = null;curr = null;
        return result;
    }

 

posted @ 2021-01-12 16:33  下课后我要去放牛  阅读(587)  评论(0编辑  收藏  举报