Java Calendar Between daysBetween(final Calendar startDate, final Calendar endDate)

Here you can find the source of daysBetween(final Calendar startDate, final Calendar endDate)

Description

Determines the number of days between two dates in Calendar objects

License

Apache License

Parameter

Parameter Description
startDate a parameter
endDate a parameter

Return

the difference in days

Declaration

public static long daysBetween(final Calendar startDate, final Calendar endDate) 

Method Source Code


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

import java.util.Calendar;

public class Main {
    /**//from  w  w  w. java  2  s  .c o  m
     * Determines the number of days between two dates in Calendar objects
     * @param startDate
     * @param endDate
     * @return the difference in days
     */
    public static long daysBetween(final Calendar startDate, final Calendar endDate) {
        Calendar sDate = (Calendar) startDate.clone();
        long daysBetween = 0;

        int y1 = sDate.get(Calendar.YEAR);
        int y2 = endDate.get(Calendar.YEAR);
        int m1 = sDate.get(Calendar.MONTH);
        int m2 = endDate.get(Calendar.MONTH);

        // **year optimization**
        while (((y2 - y1) * 12 + (m2 - m1)) > 12) {

            // move to Jan 01
            if (sDate.get(Calendar.MONTH) == Calendar.JANUARY
                    && sDate.get(Calendar.DAY_OF_MONTH) == sDate.getActualMinimum(Calendar.DAY_OF_MONTH)) {

                daysBetween += sDate.getActualMaximum(Calendar.DAY_OF_YEAR);
                sDate.add(Calendar.YEAR, 1);
            } else {
                int diff = 1 + sDate.getActualMaximum(Calendar.DAY_OF_YEAR) - sDate.get(Calendar.DAY_OF_YEAR);
                sDate.add(Calendar.DAY_OF_YEAR, diff);
                daysBetween += diff;
            }
            y1 = sDate.get(Calendar.YEAR);
        }

        // ** optimize for month **
        // while the difference is more than a month, add a month to start month
        while ((m2 - m1) % 12 > 1) {
            daysBetween += sDate.getActualMaximum(Calendar.DAY_OF_MONTH);
            sDate.add(Calendar.MONTH, 1);
            m1 = sDate.get(Calendar.MONTH);
        }

        // process remainder date
        while (sDate.before(endDate)) {
            sDate.add(Calendar.DAY_OF_MONTH, 1);
            daysBetween++;
        }

        return daysBetween;
    }
}

Related

  1. daysBetween(Calendar fromCalendar, Calendar untilCalendar)
  2. daysBetween(Calendar fromDate, Calendar toDate)
  3. daysBetween(Calendar start, Calendar end)
  4. daysBetween(Calendar startTime, Calendar endTime)
  5. daysBetween(final Calendar cal1, final Calendar cal2)
  6. daysBetween(final Calendar startDate, final Calendar endDate)
  7. daysBetweenCalendarDates(final Calendar firstDate, final Calendar secondDate)
  8. daysBetweenForDate(Calendar startDate, Calendar endDate)
  9. daysBetweenxX(Calendar start, Calendar end)