Java Utililty Methods Date Difference

List of utility methods to do Date Difference

Description

The list of methods to do Date Difference are organized into topic(s).

Method

longdiff(int type, Date date1, Date date2)
diff
switch (type) {
case Calendar.YEAR:
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date1);
    long time = calendar.get(Calendar.YEAR);
    calendar.setTime(date2);
    return time - calendar.get(Calendar.YEAR);
case Calendar.DATE:
...
intdiff_in_date(Date d1, Date d2, String type)
difidate
if (type.endsWith("day"))
    return (int) (d1.getTime() - d2.getTime()) / 86400000;
else if (type.endsWith("hour"))
    return (int) (d1.getTime() - d2.getTime()) / 3600000;
else if (type.endsWith("min"))
    return (int) (d1.getTime() - d2.getTime()) / 60000;
else
    return (int) (d1.getTime() - d2.getTime()) / 86400000;
...
LongdiffBetweenMonth(Date d1, Date d2)
diff Between Month
Calendar cal1 = new GregorianCalendar();
cal1.setTime(d1);
Calendar cal2 = new GregorianCalendar();
cal2.setTime(d2);
long month = (cal2.get(Calendar.YEAR) - cal1.get(Calendar.YEAR)) * 12 + cal2.get(Calendar.MONTH)
        - cal1.get(Calendar.MONTH);
return month;
intdiffCommercial(Date dateUntil, Date dateFrom, boolean bAddDay)
returns the commercial day difference between two dates
int result = 0;
if (dateFrom.after(dateUntil)) {
    result = -1;
} else if (dateFrom.equals(dateUntil)) {
    result = (bAddDay ? 1 : 0);
} else {
    final Calendar calFrom = new GregorianCalendar();
    calFrom.setTime(dateFrom);
...
longdiffDate(Date date, Date date1)
diff Date
return (getMillis(date) - getMillis(date1)) / 86400000L;
intdiffDate(java.util.Date date, java.util.Date date1)
diff Date
return (int) ((getMillis(date) - getMillis(date1)) / (24 * 3600 * 1000));
intdiffDateD(Date sd, Date ed)
diff Date D
return Math.round((float) (ed.getTime() - sd.getTime()) / 86400000) + 1;
intdiffDateM(Date sd, Date ed)
Get the total month from two date.
Calendar c_sd = Calendar.getInstance();
Calendar c_ed = Calendar.getInstance();
c_sd.setTime(sd);
c_ed.setTime(ed);
return (c_ed.get(Calendar.YEAR) - c_sd.get(Calendar.YEAR)) * 12 + c_ed.get(Calendar.MONTH)
        - c_sd.get(Calendar.MONTH) + 1;
longdiffDates(long starttime, long endtime, int type)
diff Dates
long result = endtime - starttime;
switch (type) {
case 1:
    result = result / (1000 * 60 * 60 * 24 * 365);
    break;
case 2:
    result = result / (1000 * 60 * 60 * 24 * 30);
    break;
...
longdiffDateSec(java.util.Date date, java.util.Date date1)
diff Date Sec
long t1 = date1.getTime();
long t2 = date.getTime();
long millis = t2 - t1;
long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);
return seconds;