Java Date Difference dateDiff(final Date date1, final Date date2)

Here you can find the source of dateDiff(final Date date1, final Date date2)

Description

Calculate difference in milliseconds from 2 dates.

License

LGPL

Parameter

Parameter Description
date1 First date
date2 Second date

Return

Difference between first date and second date in milliseconds

Declaration

public static long dateDiff(final Date date1, final Date date2) 

Method Source Code

//package com.java2s;
//License from project: LGPL 

import java.util.*;

public class Main {
    /**//  w ww. j ava2  s.  c om
     * Milliseconds=14 *
     */
    public static final int MILLISECOND = Calendar.MILLISECOND;
    /**
     * Seconds=13 *
     */
    public static final int SECOND = Calendar.SECOND;
    /**
     * Minute=12 *
     */
    public static final int MINUTE = Calendar.MINUTE;
    /**
     * Hour=11 *
     */
    public static final int HOUR = Calendar.HOUR_OF_DAY;
    /**
     * Day=5 *
     */
    public static final int DAY = Calendar.DAY_OF_MONTH;

    /**
     * Calculate difference in milliseconds from 2 dates.
     *
     * @param date1 First date
     * @param date2 Second date
     * @return Difference between first date and second date in milliseconds
     */
    public static long dateDiff(final Date date1, final Date date2) {
        long result = date1.getTime() - date2.getTime();
        return result;
    }

    /**
     * Calculate difference from 2 dates.<br>
     * Result is in "measureUnit" measure unit. (Ex: DAY)
     *
     * @param date1       First date
     * @param date2       Second date
     * @param measureUnit Measure unit. Ex: DateUtility.DAY
     * @return Difference between first date and second date.
     */
    public static double dateDiff(final Date date1, final Date date2, int measureUnit) {
        long diff = dateDiff(date1, date2);
        double result = 0d;
        switch (measureUnit) {
        case MILLISECOND:
            result = (double) diff;
            break;
        case SECOND:
            result = (double) (diff / 1000d);
            break;
        case MINUTE:
            result = (double) (diff / (1000d * 60L));
            break;
        case HOUR:
            result = (double) (diff / (1000d * 60d * 60d));
            break;
        case DAY:
            result = (double) (diff / (1000d * 60d * 60d * 24d));
            break;
        }
        return result;
    }
}

Related

  1. dateDiff(Date date1, Date date2)
  2. dateDiff(Date date1, Date date2)
  3. dateDiff(Date date1, Date date2)
  4. dateDiff(Date fromDate, Date toDate)
  5. DateDiff(Date startDate, Date endDate)
  6. dateDiff(int category, Date date1, Date date2)
  7. dateDiff(int interval, Date begin, Date end)
  8. dateDiff(java.util.Date a, java.util.Date b)
  9. dateDiff(String startDate, String endDate)