java计算时间段内有多少个月
public static void main(String[] args) throws ParseException { Calendar c1 = Calendar.getInstance();//实例化 Calendar c2 = Calendar.getInstance(); SimpleDateFormat sdf=new SimpleDateFormat("yyyyMM"); String s = "202103"; String s2 = "202010"; Date date1 = sdf.parse(s); Date date2 = sdf.parse(s2); c1.setTime(date1);//设置传入的日期 c2.setTime(date2); int year1 = c1.get(Calendar.YEAR);//获取年 int year2 = c2.get(Calendar.YEAR); int month1 = c1.get(Calendar.MONTH);//月份 int month2 = c2.get(Calendar.MONTH); int day1 = c1.get(Calendar.DAY_OF_MONTH);//日 int day2 = c2.get(Calendar.DAY_OF_MONTH); // 获取年的差值 int yearInterval = year1 - year2; // 如果 d1的 月-日 小于 d2的 月-日 那么 yearInterval-- 这样就得到了相差的年数 if (month1 < month2 || month1 == month2 && day1 < day2) yearInterval--; // 获取月数差值 int monthInterval = (month1 + 12) - month2; if (day1 < day2) monthInterval--; monthInterval %= 12; int monthsDiff = Math.abs(yearInterval * 12 + monthInterval); System.out.printf(String.valueOf(monthsDiff)); }