public static String[] getAllMonths(String start, String end) { String regex = "\\d{4}(([0][1-9])|([1][012]))"; //判断YYYY-MM时间格式的正则表达式 if (!start.matches(regex) || !end.matches(regex)) return new String[0]; List<String> list = new ArrayList<>(); if (start.compareTo(end) == 0) { String[] result = new String[1]; result[0] = start; return result; } if (start.compareTo(end) > 0) { //start大于end日期时,互换 String temp = start; start = end; end = temp; } String temp = start; //从最小月份开始 while (temp.compareTo(start) >= 0 && temp.compareTo(end) <= 0) { list.add(temp); //首先加上最小月份,接着计算下一个月份 //String[] arr=temp.split(splitSign); int year = Integer.valueOf(temp.substring(0, 4)); int month = Integer.valueOf(temp.substring(4, 6)) + 1; if (month > 12) { month = 1; year++; } if (month < 10) {//补0操作 temp = year + "0" + month; } else { temp = year + "" + month; } } int size = list.size(); String[] result = new String[size]; for (int i = 0; i < size; i++) { result[i] = list.get(i); } return result; }
public static void main(String[] args) {
String[] strs= getAllMonths("202101","202112");
if(strs!=null&&strs.length>0){
for (String str:strs) {
System.out.println(str);
}
}
}
执行结果: