Here you can find the source of calculateDifference(Date d1, Date d2)
public static String calculateDifference(Date d1, Date d2)
//package com.java2s; import java.util.Calendar; import java.util.Date; public class Main { public static String calculateDifference(Date d1, Date d2) { Calendar startDate = Calendar.getInstance(); Calendar endDate = Calendar.getInstance(); startDate.clear();/* w w w .j a v a2 s . com*/ endDate.clear(); startDate.setTime(d1); endDate.setTime(d2); if ((startDate == null) || (endDate == null) || startDate.after(endDate)) { return ""; } int yearDiff = endDate.get(Calendar.YEAR) - startDate.get(Calendar.YEAR); boolean bYearAdjusted = false; startDate.add(Calendar.YEAR, yearDiff); if (startDate.after(endDate)) { bYearAdjusted = true; startDate.add(Calendar.YEAR, -1); yearDiff--; } int monthDiff = endDate.get(Calendar.MONTH) - startDate.get(Calendar.MONTH); if (bYearAdjusted && (monthDiff <= 0)) { monthDiff = 12 + monthDiff; } startDate.add(Calendar.MONTH, monthDiff); if (startDate.after(endDate)) { startDate.add(Calendar.MONTH, -1); monthDiff--; } int dayDiff = endDate.get(Calendar.DAY_OF_YEAR) - startDate.get(Calendar.DAY_OF_YEAR); if (dayDiff < 0) { dayDiff = 365 + dayDiff; } startDate.add(Calendar.DAY_OF_YEAR, dayDiff); StringBuffer buffer = new StringBuffer(); if (yearDiff > 0) { buffer.append(yearDiff).append(" Year(s), "); buffer.append(monthDiff).append(" Month(s), "); } else if (monthDiff > 0) { buffer.append(monthDiff).append(" Month(s), "); } buffer.append(dayDiff).append(" Day(s)"); return buffer.toString(); } public static String toString(String str, char separator, int radix) { byte[] value = str.getBytes(); int digits = (int) (Math.round((float) Math.log(256) / Math.log(radix))); StringBuffer buf = new StringBuffer(value.length * (digits + 1)); for (int i = 0; i < value.length; i++) { if (i > 0) { buf.append(separator); } int v = (value[i] & 0xFF); String val = Integer.toString(v, radix); for (int j = 0; j < digits - val.length(); j++) { buf.append('0'); } buf.append(val); } return buf.toString(); } }