Java Date Difference dateDiff(java.util.Date a, java.util.Date b)

Here you can find the source of dateDiff(java.util.Date a, java.util.Date b)

Description

Date diff.

License

Apache License

Parameter

Parameter Description
a the a
b the b

Return

the int

Declaration

public static int dateDiff(java.util.Date a, java.util.Date b) 

Method Source Code

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

import java.util.Calendar;

public class Main {
    /**/*from w w w.j a va  2s. c  om*/
     * Date diff.
     *
     * @param a the a
     * @param b the b
     * @return the int
     */
    public static int dateDiff(java.util.Date a, java.util.Date b) {
        int tempDifference = 0;
        int difference = 0;
        Calendar earlier = Calendar.getInstance();
        Calendar later = Calendar.getInstance();

        if (a.compareTo(b) < 0) {
            earlier.setTime(a);
            later.setTime(b);
        } else {
            earlier.setTime(b);
            later.setTime(a);
        }

        while (earlier.get(Calendar.YEAR) != later.get(Calendar.YEAR)) {
            tempDifference = 365 * (later.get(Calendar.YEAR) - earlier.get(Calendar.YEAR));
            difference += tempDifference;

            earlier.add(Calendar.DAY_OF_YEAR, tempDifference);
        }

        if (earlier.get(Calendar.DAY_OF_YEAR) != later.get(Calendar.DAY_OF_YEAR)) {
            tempDifference = later.get(Calendar.DAY_OF_YEAR) - earlier.get(Calendar.DAY_OF_YEAR);
            difference += tempDifference;

            earlier.add(Calendar.DAY_OF_YEAR, tempDifference);
        }

        return difference;
    }
}

Related

  1. dateDiff(Date fromDate, Date toDate)
  2. DateDiff(Date startDate, Date endDate)
  3. dateDiff(final Date date1, final Date date2)
  4. dateDiff(int category, Date date1, Date date2)
  5. dateDiff(int interval, Date begin, Date end)
  6. dateDiff(String startDate, String endDate)
  7. dateDiff(String startTime, String endTime, String format)
  8. DateDiff(String strDateBegin, String strDateEnd, int iType)
  9. dateDiffer(String time1, String time2, String formatStr)