Here you can find the source of calculateDifferMonths(Date date1, Date date2, boolean isTruncate)
private static int calculateDifferMonths(Date date1, Date date2, boolean isTruncate)
//package com.java2s; //License from project: Apache License import java.util.Calendar; import java.util.Date; public class Main { private static int calculateDifferMonths(Date date1, Date date2, boolean isTruncate) { final int[] bgnDate, endDate; if (date1.getTime() > date2.getTime()) { bgnDate = getYearMonthDay(date2); endDate = getYearMonthDay(date1); } else {// w ww .ja va 2 s . c om bgnDate = getYearMonthDay(date1); endDate = getYearMonthDay(date2); } final int endMonth; if (!isTruncate || endDate[2] >= bgnDate[2]) { endMonth = endDate[1]; } else { endMonth = endDate[1] - 1; } if (endMonth >= bgnDate[1]) { return (endDate[0] - bgnDate[0]) * 12 + (endMonth - bgnDate[1]); } else { return (endDate[0] - bgnDate[0] - 1) * 12 + (12 + endMonth - bgnDate[1]); } } public static int[] getYearMonthDay(Date date) { Calendar bgnDate = Calendar.getInstance(); bgnDate.setTime(date); return new int[] { bgnDate.get(Calendar.YEAR), bgnDate.get(Calendar.MONTH) + 1, bgnDate.get(Calendar.DATE) }; } }