public class DateUtil { public static int getDay(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.DATE); } public static int getMonth(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.MONTH) + 1; } public static int getYear(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.YEAR); } public static int getDaysOfMonth(int year, int month) { Calendar calendar = Calendar.getInstance(); calendar.set(year, month - 1, 1); return calendar.getActualMaximum(Calendar.DAY_OF_MONTH); } public static int calDiffMonth(String startDate,String endDate){ int result=0; try { SimpleDateFormat sfd=new SimpleDateFormat("yyyy-MM-dd"); Date start = sfd.parse(startDate); Date end = sfd.parse(endDate); int startYear=getYear(start); int startMonth=getMonth(start); int startDay=getDay(start); int endYear=getYear(end); int endMonth=getMonth(end); int endDay=getDay(end); if (startDay>endDay){ //1月17 大于 2月28 if (endDay==getDaysOfMonth(getYear(new Date()),2)){ //也满足一月 result=(endYear-startYear)*12+endMonth-startMonth; }else{ result=(endYear-startYear)*12+endMonth-startMonth-1; } }else{ result=(endYear-startYear)*12+endMonth-startMonth; } } catch (ParseException e) { e.printStackTrace(); } return result; } //测试正确 public static void main(String[] args) { int i = calDiffMonth("2017-06-30", "2018-07-01"); System.out.println(i); }}