Here you can find the source of getDifference(int field, Calendar aCalX, Calendar aCalY)
public static final int getDifference(int field, Calendar aCalX, Calendar aCalY)
//package com.java2s; import java.util.Calendar; import java.util.GregorianCalendar; public class Main { public static final int getDifference(int field, Calendar aCalX, Calendar aCalY) { int gap = 0; int step = 0; Calendar calX = new GregorianCalendar(); Calendar calY = new GregorianCalendar(); calX.set(aCalX.get(Calendar.YEAR), aCalX.get(Calendar.MONTH), aCalX.get(Calendar.DATE), 0, 0, 0); calY.set(aCalY.get(Calendar.YEAR), aCalY.get(Calendar.MONTH), aCalY.get(Calendar.DATE), 0, 0, 0); step = (calX.before(calY) ? -1 : 1); if (field == Calendar.DATE) { while (!calX.equals(calY)) { calY.add(Calendar.DATE, step); gap = gap + step;// w w w. j av a2s. com } } else if (field == Calendar.MONTH) { calX.set(calX.get(Calendar.YEAR), calX.get(Calendar.MONTH), 1); calY.set(calY.get(Calendar.YEAR), calY.get(Calendar.MONTH), 1); while (!calX.equals(calY)) { calY.add(Calendar.MONTH, step); gap = gap + step; } } else if (field == Calendar.YEAR) { calX.set(calX.get(Calendar.YEAR), 1, 1); calY.set(calY.get(Calendar.YEAR), 1, 1); while (!calX.equals(calY)) { calY.add(Calendar.YEAR, step); gap = gap + step; } } return gap; } }