Java Day Between getDaysBetween(Date startDate, Date endDate)

Here you can find the source of getDaysBetween(Date startDate, Date endDate)

Description

Returns the number of calendar days between two dates.

License

Open Source License

Parameter

Parameter Description
startDate start date
endDate end date

Return

number of days between start date and end date (-1 if the former is after the latter)

Declaration

public static int getDaysBetween(Date startDate, Date endDate) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright 2008(c) The OBiBa Consortium. All rights reserved.
 *
 * This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/

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

public class Main {
    /**/*from w ww .  j a va  2  s  .c o m*/
     * Returns the number of calendar days between two dates.
     *
     * @param startDate start date
     * @param endDate end date
     * @return number of days between start date and end date (<code>-1</code> if the former is after the latter)
     */
    public static int getDaysBetween(Date startDate, Date endDate) {
        int daysBetween = -1;

        if (startDate.after(endDate))
            return daysBetween;

        Calendar c = Calendar.getInstance();

        if (startDate.after(endDate))
            return daysBetween;

        c.setTime(startDate);
        int startYear = c.get(Calendar.YEAR);
        int startDay = c.get(Calendar.DAY_OF_YEAR);

        c.setTime(endDate);
        int endYear = c.get(Calendar.YEAR);
        int endDay = c.get(Calendar.DAY_OF_YEAR);

        if (startYear == endYear) {
            daysBetween = endDay - startDay;
        } else {
            c.setTime(startDate);
            daysBetween = c.getActualMaximum(Calendar.DAY_OF_YEAR) - startDay;

            for (int year = startYear + 1; year < endYear; year++) {
                c.set(Calendar.YEAR, year);
                daysBetween += c.getActualMaximum(Calendar.DAY_OF_YEAR);
            }

            daysBetween += endDay;
        }

        return daysBetween;
    }
}

Related

  1. getDateWithDiff(Date date, int amount)
  2. getDaysBetween(Date date1, Date date2)
  3. getDaysBetween(Date start, Date end)
  4. getDaysBetween(Date start, Date end)
  5. getDaysBetween(Date startDate, Date endDate)
  6. getDaysBetweenDate(Date begin, Date end)
  7. getDaysDiff(Date startDate, Date endDate)
  8. getDaysDifference(final Date begin, final Date end)
  9. getDiffBetweenQuarter(Date latestDate, Date current)