Java Day Between getDaysBetween(Date date1, Date date2)

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

Description

gets days between any two dates (integer form) regardless of order

License

Open Source License

Parameter

Parameter Description
date1 first date (Date)
date2 second date (Date)

Declaration

public static int getDaysBetween(Date date1, Date date2) 

Method Source Code

//package com.java2s;
/*//from w  w w. j a v a2 s  . c om
 *  DateUtil.java
 *  Copyright (C) 2011 Dale Furrow
 *  dkfurrow@google.com
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public License
 *  as published by the Free Software Foundation; either version 3
 *  of the License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with this program; if not, a copy may be found at
 *  http://www.gnu.org/licenses/lgpl.html
 */

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

public class Main {
    /**
    * gets days between any two dates (integer form) regardless of order
    * @param date1 first date (Date)
    * @param date2 second date (Date)
    * @return
    */
    public static int getDaysBetween(Date date1, Date date2) {
        GregorianCalendar d1 = new GregorianCalendar();
        d1.setTime(date1);
        GregorianCalendar d2 = new GregorianCalendar();
        d2.setTime(date2);

        if (d1.after(d2)) {
            // swap dates so that d1 is start and d2 is end
            GregorianCalendar swap = d1;
            d1 = d2;
            d2 = swap;
        }

        int days = d2.get(Calendar.DAY_OF_YEAR) - d1.get(Calendar.DAY_OF_YEAR);
        int y2 = d2.get(Calendar.YEAR);
        if (d1.get(Calendar.YEAR) != y2) {
            d1 = (GregorianCalendar) d1.clone();
            do {
                days += d1.getActualMaximum(Calendar.DAY_OF_YEAR);
                d1.add(Calendar.YEAR, 1);
            } while (d1.get(Calendar.YEAR) != y2);
        }
        return days;
    }
}

Related

  1. getDateDiff(final Date startDate, final Date endDate)
  2. getDateDifference(Date date1, Date date2)
  3. getDateDifferenceinDays(Date date1, Date date2)
  4. getDateDiffYear(Date date, int diff, String... format)
  5. getDateWithDiff(Date date, int amount)
  6. getDaysBetween(Date start, Date end)
  7. getDaysBetween(Date start, Date end)
  8. getDaysBetween(Date startDate, Date endDate)
  9. getDaysBetween(Date startDate, Date endDate)