Java Day Between calculateDayDifference(final Date a, final Date b)

Here you can find the source of calculateDayDifference(final Date a, final Date b)

Description

This method calculates the difference between 2 dates.

License

Open Source License

Parameter

Parameter Description
a The first date.
b The second date.

Return

The difference.

Declaration

public static int calculateDayDifference(final Date a, final Date b) 

Method Source Code

//package com.java2s;
/**/*ww w . j  a  va  2 s  .c o m*/
 * ? 2003 Cordys R&D B.V. All rights reserved. The computer program(s) is the proprietary information of Cordys R&D B.V. and
 * provided under the relevant License Agreement containing restrictions on use and disclosure. Use is subject to the License
 * Agreement.
 */

import java.util.Calendar;
import java.util.Date;

public class Main {
    /**
     * This method calculates the difference between 2 dates.
     * 
     * @param a The first date.
     * @param b The second date.
     * @return The difference.
     */
    public static int calculateDayDifference(final Date a, final 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. calculateDays(Date beginDate, Date endDate)
  2. calculateDays(Date dateEarly, Date dateLater)
  3. calculateDifference(Date d1, Date d2)
  4. calculateDifferMonths(Date date1, Date date2, boolean isTruncate)