比如开始时间传入2020-01 结束时间传入2020-12,那么最后返回的集合就是2020-01,-02,-03…-12
/**
* 获取两个日期之间的所有月份 (年月或者年或者年月日都可以)
*
* @param startTime 开始时间
* @param endTime 结束时间
* @return:YYYY-MM
*/
public static List<String> getMonthBetweenDate(String startTime, String endTime) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
// 声明保存日期集合
List<String> list = new ArrayList<String>();
try {
// 转化成日期类型
Date startDate = sdf.parse(startTime);
Date endDate = sdf.parse(endTime);
//用Calendar 进行日期比较判断
Calendar calendar = Calendar.getInstance();
while (startDate.getTime() <= endDate.getTime()) {
// 把日期添加到集合
list.add(sdf.format(startDate));
// 设置日期
calendar.setTime(startDate);
//把日期增加一月
calendar.add(Calendar.MONTH, 1);
// 获取增加后的日期
startDate = calendar.getTime();
}
} catch (ParseException e) {
e.printStackTrace();
}
return list;
}