Here you can find the source of getIntervalYears(Date date1, Date date2)
public static int getIntervalYears(Date date1, Date date2)
//package com.java2s; import java.util.Calendar; import java.util.Date; public class Main { public static int getIntervalYears(Date date1, Date date2) { Calendar firstCal = Calendar.getInstance(); Calendar secondCal = Calendar.getInstance(); firstCal.setTime(date1);/*from www . ja v a 2 s. c om*/ secondCal.setTime(date2); int year = firstCal.get(Calendar.YEAR) - secondCal.get(Calendar.YEAR); int month = firstCal.get(Calendar.MONTH) - secondCal.get(Calendar.MONTH); int day = firstCal.get(Calendar.DAY_OF_MONTH) - secondCal.get(Calendar.DAY_OF_MONTH); year = year - ((month > 0) ? 0 : ((month < 0) ? 1 : ((day >= 0 ? 0 : 1)))); month = (month < 0) ? (day > 0 ? 12 + month : 12 + month - 1) : (day >= 0 ? month : month - 1); firstCal.add(Calendar.MONTH, -1); day = (day < 0) ? (perMonthDays(firstCal)) + day : day; int timeStr = year; return timeStr; } public static int perMonthDays(Calendar cal) { int maxDays = 0; int month = cal.get(Calendar.MONTH); switch (month) { case Calendar.JANUARY: case Calendar.MARCH: case Calendar.MAY: case Calendar.JULY: case Calendar.AUGUST: case Calendar.OCTOBER: case Calendar.DECEMBER: maxDays = 31; break; case Calendar.APRIL: case Calendar.JUNE: case Calendar.SEPTEMBER: case Calendar.NOVEMBER: maxDays = 30; break; case Calendar.FEBRUARY: if (isLeap(cal.get(Calendar.YEAR))) { maxDays = 29; } else { maxDays = 28; } break; } return maxDays; } public static boolean isLeap(int year) { boolean leap = false; if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { leap = true; } return leap; } }