Here you can find the source of dateDiff(Date d1, Date d2, int field)
public static long dateDiff(Date d1, Date d2, int field)
//package com.java2s; //License from project: Apache License import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class Main { public static long dateDiff(Date d1, Date d2, int field) { long j = 1; switch (field) { case Calendar.YEAR: return dateDiffYear(d1, d2); case Calendar.MONTH: return dateDiffMonth(d1, d2); case Calendar.DATE: j = 1000 * 60 * 60 * 24;// w w w . j a v a 2 s . c o m break; case Calendar.HOUR: j = 1000 * 60 * 60; break; case Calendar.MINUTE: j = 1000 * 60; break; case Calendar.SECOND: j = 1000; break; default: return 0; } long diff = d1.getTime() - d2.getTime(); return diff / j; } public static long dateDiffYear(Date d1, Date d2) { Calendar calendar = Calendar.getInstance(); calendar.setTime(d1); int i = calendar.get(Calendar.YEAR); calendar.setTime(d2); int j = calendar.get(Calendar.YEAR); return i - j; } public static long dateDiffMonth(Date d1, Date d2) { Calendar calendar = Calendar.getInstance(); calendar.setTime(d1); int y1 = calendar.get(Calendar.YEAR); int m1 = calendar.get(Calendar.MONTH); calendar.setTime(d2); int y2 = calendar.get(Calendar.YEAR); int m2 = calendar.get(Calendar.MONTH); return (y1 - y2) * 12 + m1 - m2; } public static Date getTime(String date) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return sdf.parse(date); } public static int get(Date date, int field) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(field); } }