【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 @ 2024-05-10 20:45  萌狼蓝天  阅读(10)  评论(0编辑  收藏  举报