Here you can find the source of getIntervalMonths(String startDate, String endDate)
public static int getIntervalMonths(String startDate, String endDate)
//package com.java2s; //License from project: Open Source License import java.text.SimpleDateFormat; import java.util.Date; public class Main { public static int getIntervalMonths(String startDate, String endDate) { startDate = startDate.replaceAll("-", ""); StringBuffer sb = new StringBuffer(startDate); sb.insert(4, "-"); startDate = startDate.length() == 6 ? sb.append("-01").toString() : sb.insert(7, "-").toString(); endDate = endDate.replaceAll("-", ""); StringBuffer sb1 = new StringBuffer(endDate); sb1.insert(4, "-"); endDate = endDate.length() == 6 ? sb1.append("-01").toString() : sb1.insert(7, "-").toString(); Date st = parseStringToUtilDate(startDate); Date et = parseStringToUtilDate(endDate); String sy = getYear(st);//from ww w . j av a 2 s .c o m String ey = getYear(et); int MonthByYear = 0; int reVal = Integer.valueOf(getMonth(et)).intValue() - Integer.valueOf(getMonth(st)).intValue(); if (!sy.equals("ey")) { MonthByYear = (Integer.valueOf(ey).intValue() - Integer.valueOf(sy).intValue()) * 12; } return MonthByYear + reVal; } public static java.util.Date parseStringToUtilDate(String strDate) { java.util.Date date = null; try { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); date = df.parse(strDate); } catch (Exception ex) { ex.printStackTrace(); } return date; } public static String getYear(Date date) { if (null == date) { return null; } SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy"); return yearFormat.format(date); } public static String getMonth(Date date) { if (null == date) { return null; } SimpleDateFormat yearFormat = new SimpleDateFormat("MM"); return yearFormat.format(date); } }