编程语言
首页 > 编程语言> > Java获取两个时间段之间的每个年月或者月初的值

Java获取两个时间段之间的每个年月或者月初的值

作者:互联网

1. 求两个年月之间的月份,包含开始月份

    /**
     * @param startMonth @example: "2016-01"
     * @param endMonth @example: "2019-11"
     * @return    两个时间之间的月份(含开始,结束)
     * @throws ParseException 
     */
    private List<String> getMonths(String startMonth,String endMonth) throws ParseException{
        LinkedList<String> months = new LinkedList<>();
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Calendar minCalender = Calendar.getInstance();
        Calendar maxCalender = Calendar.getInstance();
        
                // 设置开始月份
        minCalender.setTime(sdf.parse(startMonth));
        minCalender.set(minCalender.get(Calendar.YEAR), minCalender.get(Calendar.MONTH),1);
        
        maxCalender.setTime(sdf.parse(endMonth));
                // 设置日期,保证最后一个日期参数 大于 开始时间日历
        maxCalender.set(maxCalender.get(Calendar.YEAR), maxCalender.get(Calendar.MONTH),2);
        
        while (minCalender.before(maxCalender)) {
            months.add(sdf.format( minCalender.getTime() ));
            minCalender.add(Calendar.MONTH, 1);
        }
        return months;
    }

2. 求两个年月之间的月份,包含开始月份,不含结束月份

    /**
     * @param startMonth @example: "2016-01"
     * @param endMonth @example: "2019-11"
     * @return    两个时间之间的月份(含开始,不含结束)
     * @throws ParseException 
     */
    private List<String> getMonths(String startMonth,String endMonth) throws ParseException{
        LinkedList<String> months = new LinkedList<>();
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Calendar minCalender = Calendar.getInstance();
        Calendar maxCalender = Calendar.getInstance();
        
                // 设置开始月份
        minCalender.setTime(sdf.parse(startMonth));
                // 设置结束月份
        maxCalender.setTime(sdf.parse(endMonth));
        
        while (minCalender.before(maxCalender)) {
            months.add(sdf.format( minCalender.getTime() ));
            minCalender.add(Calendar.MONTH, 1);
        }
        return months;
    }

 

标签:minCalender,Java,startMonth,endMonth,获取,sdf,时间段,Calendar,maxCalender
来源: https://www.cnblogs.com/mike-mei/p/16179946.html