传入年月,遍历返回中间所有的月份(包含起始月和结尾月份)

传入年月,遍历中间所有的月份(包含起始月和结尾月份)

今天遇到个需求:选择两个月份,需要两个月中间的每个月的统计数据,原本的意思是从数据库直接查出来,再通过日期赋值。
但是考虑到这样一种情况:万一某个月中间没有数据,那岂不是为空!
所有还得遍历每一个月份,对于没有数据的月份,在对于月份中设置为0就行。

下面是我写的工具类:注意传入的格式(YYYY-MM)字符串类型的年和月

/**
 * @Description:
 * @author: wangyong
 * @date: 2022年05月11日 20:36
 */
public class DateUtils {

    /**
     *  传入年月,遍历中间所有的月份(包含起始月和结尾月份)
     * @param startDate 起始月 yyyy-mm
     * @param endDate 结束月 yyyy-mm
     * @return
     */
    public static List<String> getBetweenYearMonth(String startDate,String endDate){
        Integer startY = Integer.valueOf(startDate.split("-")[0]);
        Integer startM = Integer.valueOf(startDate.split("-")[1]);
        Integer endY = Integer.valueOf(endDate.split("-")[0]);
        Integer endM = Integer.valueOf(endDate.split("-")[1]);
        //用来格式化
        DecimalFormat decimalFormat = new DecimalFormat("00");
        List<String> list = new ArrayList<>();
        if (startY > endY){
            throw new MyServiceException("日期格式不正确不对");
        }
        //年份相同的时候
        if (startY.equals(endY)&&endM-startM>=0){
            int count=startM;
            while (endM-count>=0){
                list.add(startY+"-"+decimalFormat.format(count));
                count++;
            }
        }else{
            int year = startY;
            int month = startM;
            //年份不同
            while (endY-year>0){
                for (int i = month; i <= 12 ; i++) {
                    list.add(year+"-"+decimalFormat.format(i));
                }
                year++;
                month=1;
                if (year==endY){
                    for (int i = 1; i <= endM; i++) {
                        list.add(year+"-"+decimalFormat.format(i));
                    }
                }
            }
        }
        return list;
    }
    public static void main(String[] args) {
        System.out.println(getBetweenYearMonth("2020-05", "2022-10"));
    }
}	

测试结果如下

[2020-05, 2020-06, 2020-07, 2020-08, 2020-09, 2020-10, 2020-11, 2020-12, 2021-01, 2021-02, 2021-03, 2021-04, 2021-05, 2021-06, 2021-07, 2021-08, 2021-09, 2021-10, 2021-11, 2021-12, 2022-01, 2022-02, 2022-03, 2022-04, 2022-05, 2022-06, 2022-07, 2022-08, 2022-09, 2022-10]
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值