獲取兩個日期間的所有月份
public void getMonthOfYear() throws ParseException {
String dateString1 = "2019-01";//開始日期,格式要根據getInitMonthMapWithZero2方法中的日期轉換格式匹配上
String dateString2 = "2020-09";//結束日期
List<String> list = new ArrayList<String>();
List<String> initMonthMapWithZero2 = getInitMonthMapWithZero2(list,dateString1,dateString2);
for (String string : initMonthMapWithZero2) {
System.out.println(string);
}
}
public List<String> getInitMonthMapWithZero2(List<String> myList,String beginTime,String endTime) throws ParseException {
List<String> list = myList;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
Date endDate = dateFormat.parse(endTime);
if(!myList.contains(beginTime)) {
Calendar c = Calendar.getInstance();
c.setTime(endDate);
for(int i = 0; i < 12; i ++){
int k = c.get(Calendar.YEAR);
int j = c.get(Calendar.MONTH) + 1 - i;
String date = "";
if(j >= 1){
date = k + "-" + (j >= 10 ? "" : "0") + j;
}else {
int p = 11 - i;//剩餘循環次數
int m = c.get(Calendar.YEAR) - 1;
int n = c.get(Calendar.MONTH) + 2 + p;
date = m + "-" + (n >= 10 ? "" : "0") + n;
}
if(list.contains(endTime)&&endTime.equals(date)) {
continue;
}else {
list.add(date);
}
if(date.equals(beginTime)) {
return list;
}
}
getInitMonthMapWithZero2(list,beginTime,list.get(list.size()-1));
}
得到結果:
2020-09
2020-08
2020-07
2020-06
2020-05
2020-04
2020-03
2020-02
2020-01
2019-12
2019-11
2019-10
2019-09
2019-08
2019-07
2019-06
2019-05
2019-04
2019-03
2019-02
2019-01