List<String> dateList = new ArrayList<>(); Calendar calendar = Calendar.getInstance(); // 月份最大为11 最小为0 所以设置初始月份时加1,需要获取到当前月份所以设置初始月份时需要加2 calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + 2); for (int i = 0; i < 12; i++) { calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1); // 需要判断月份是否为0 如果0则需要转换成12,年份转为去年;,如果月份小于10,则前面加上0 dateList.add(calendar.get(Calendar.MONTH) == 0 ? calendar.get(Calendar.YEAR) - 1 + "-" + 12 : calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) < 10 ? "0" + calendar.get(Calendar.MONTH) : calendar.get(Calendar.MONTH))); }
最终出现的效果
[2023-03, 2023-02, 2023-01, 2022-12, 2022-11, 2022-10, 2022-09, 2022-08, 2022-07, 2022-06, 2022-05, 2022-04]标签:12,Java,get,MONTH,2022,Calendar,数据,calendar From: https://www.cnblogs.com/xufeng-moxuan/p/17239142.html