📂Java
🔖Java
2024-05-10 20:45阅读: 50评论: 0推荐: 0

【Java】获取近六个月的年月

数据库里面存储的字段类型就是varchar,数据格式就是类似2024-12这样的年月格式。

目标:
以当前月份为标准,向前获取近6个月的年月(year_month)形成列表

   // 获取近6个月的年月列表
        List<String> recentMonths = getRecentMonths(6);
    private List<String> getRecentMonths(int n) {
        List<String> months = new ArrayList<>();
        LocalDate now = LocalDate.now();
        for (int i = 0; i < n; i++) {
            months.add(now.minusMonths(i).format(DateTimeFormatter.ofPattern("yyyy-MM")));
        }
		
	Collections.reverse(months);
        return months;
    }

(现在是2024年5月)得到的格式如下:

image

posted @   萌狼蓝天  阅读(50)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
展开