import java.util.Calendar; import java.util.Date; public class TimeUtil { public static void main(String[] args){ System.out.println(dateDiff(new Date(), new Date(), Calendar.MINUTE)); } /** * 根据指定类型计算两个日期相差的时间 * eg. dateDiff(birth, today, Calendar.MONTH) 孩子的月龄 * @param sDate 开始时间 * @param eDate 结束时间 * @param diffType 日期类型 * @return 根据 diffType计算的 eDate - sDate 时差 */ public static Long dateDiff(Date sDate, Date eDate, int diffType) { java.util.Calendar calst = java.util.Calendar.getInstance(); java.util.Calendar caled = java.util.Calendar.getInstance(); calst.setTime(sDate); caled.setTime(eDate); long diffMill = caled.getTime().getTime() - calst.getTime().getTime(); long rtn = 0; switch (diffType) { case Calendar.MILLISECOND: rtn = diffMill; break; case Calendar.SECOND: rtn = diffMill / 1000; break; case Calendar.MINUTE: rtn = diffMill / 1000 / 60; break; case Calendar.HOUR: rtn = diffMill / 1000 / 3600; break; case Calendar.DATE: rtn = diffMill / 1000 / 60 / 60 / 24; break; case Calendar.MONTH: rtn = diffMill / 1000 / 60 / 60 / 24 / 12; break; case Calendar.YEAR: rtn = diffMill / 1000 / 60 / 60 / 24 / 365; break; } return rtn; } }