public static List<String> getMonthTimeList(Date start ,Date end) {
Calendar calStart = Calendar.getInstance();
Calendar calEnd = Calendar.getInstance();
// 格式化起始日期 和结束日期
calStart.setTime(start);
calEnd.setTime(end);
// 返回的日期集合容器
List<String> dateList = new ArrayList<>();
// 将第一个月添加进去
dateList.add(DateFormatUtils.formatDate("yyyy-MM",calStart.getTime()));
while (calEnd.getTime().after(calStart.getTime())) {
// 根据日历的规则,每次加一个月
calStart.add(Calendar.MONTH,1);
if (calStart.getTime().after(calEnd.getTime())){
// 如果最小月份等于最大月份,则跳出
continue;
}else {
dateList.add(DateFormatUtils.formatDate("yyyy-MM",calStart.getTime()));
}
}
System.out.println(dateList);
return dateList;
}
如果传进去的start为2021-09-01 10:37:43
传进去的end为2022-01-06 10:48:37
那么,输出的为
2021-09
2021-10
2021-11
2021-12
2022-01