java小工具之獲取兩個日期月份中的所有月份
阿新 • • 發佈:2021-01-12
例如:要取2019-01 到 2020-06之間的所有月份
/**獲取兩月之間的所有月份*/ public static List<String> getMonthBetween(String minDate, String maxDate){ ArrayList<String> result = new ArrayList<String>(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");//格式化為年月 Calendar min = Calendar.getInstance(); Calendar max= Calendar.getInstance(); try{ min.setTime(sdf.parse(minDate)); min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1); max.setTime(sdf.parse(maxDate)); max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2); }catch (Exception e){throw new SSCException("分解月份出錯");//注意:丟擲的型別是自定義的 } Calendar curr = min; while (curr.before(max)) { result.add(sdf.format(curr.getTime())); curr.add(Calendar.MONTH, 1); } min = null;max = null;curr = null; return result; }