栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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

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

public class DateUtils {

    
    public static List 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 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]
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/880196.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号