Java Calendar Between daysBetween(final Calendar cal1, final Calendar cal2)

Here you can find the source of daysBetween(final Calendar cal1, final Calendar cal2)

Description

days Between

License

Open Source License

Declaration

public static int daysBetween(final Calendar cal1, final Calendar cal2) 

Method Source Code

//package com.java2s;
// ProjectForge is dual-licensed.

import java.util.Calendar;

public class Main {
    public static int daysBetween(final Calendar cal1, final Calendar cal2) {
        final Calendar from, to;
        boolean positive = true;
        if (cal1.getTimeInMillis() < cal2.getTimeInMillis()) {
            from = cal1;/*from w w w  . j a  v  a2  s. c  o m*/
            to = cal2;
        } else {
            from = cal2;
            to = cal1;
            positive = false;
        }
        int result = 0;
        final int toYear = to.get(Calendar.YEAR);
        final Calendar cal = (Calendar) from.clone();

        int endlessLoopProtection = 0;
        while (cal.get(Calendar.YEAR) < toYear) {
            final int fromDay = cal.get(Calendar.DAY_OF_YEAR);
            cal.set(Calendar.MONTH, Calendar.DECEMBER);
            cal.set(Calendar.DAY_OF_MONTH, 31);
            result += cal.get(Calendar.DAY_OF_YEAR) - fromDay + 1;
            cal.add(Calendar.DAY_OF_MONTH, 1);
            if (++endlessLoopProtection > 5000) {
                throw new IllegalArgumentException("Days between doesn's support more than 5000 years");
            }
        }
        result += to.get(Calendar.DAY_OF_YEAR) - cal.get(Calendar.DAY_OF_YEAR);
        if (positive == true) {
            return result;
        } else {
            return -result;
        }
    }
}

Related

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