生成yyyyMM与yyyyMM之间的yyyyMM 格式的年月java源代码

public static String[] getAllMonths(String start, String end) {
    String regex = "\\d{4}(([0][1-9])|([1][012]))"; //判断YYYY-MM时间格式的正则表达式
    if (!start.matches(regex) || !end.matches(regex)) return new String[0];
    List<String> list = new ArrayList<>();
    if (start.compareTo(end) == 0) {
        String[] result = new String[1];
        result[0] = start;
        return result;
    }

    if (start.compareTo(end) > 0) {
        //start大于end日期时,互换
        String temp = start;
        start = end;
        end = temp;
    }

    String temp = start; //从最小月份开始
    while (temp.compareTo(start) >= 0 && temp.compareTo(end) <= 0) {
        list.add(temp); //首先加上最小月份,接着计算下一个月份
        //String[] arr=temp.split(splitSign);
        int year = Integer.valueOf(temp.substring(0, 4));
        int month = Integer.valueOf(temp.substring(4, 6)) + 1;
        if (month > 12) {
            month = 1;
            year++;
        }
        if (month < 10) {//补0操作
            temp = year + "0" + month;
        } else {
            temp = year + "" + month;
        }
    }
    int size = list.size();
    String[] result = new String[size];
    for (int i = 0; i < size; i++) {
        result[i] = list.get(i);
    }
    return result;
}

public static void main(String[] args) {

        String[] strs= getAllMonths("202101","202112");

        if(strs!=null&&strs.length>0){

        for (String str:strs) {

        System.out.println(str);

        }

  }

}

执行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值