Android Calendar Interval Get daysBetween(Calendar startDate, Calendar endDate)

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

Description

days Between

Declaration

public static int daysBetween(Calendar startDate, Calendar endDate) 

Method Source Code

//package com.java2s;
import java.util.Calendar;

public class Main {
    public static int daysBetween(Calendar startDate, Calendar endDate) {
        boolean negative = false;
        if (startDate.after(endDate)) {
            Calendar c = startDate;
            startDate = endDate;//from w ww.ja  v a  2 s  .c om
            endDate = c;
            negative = true;
        }

        int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;
        long endInstant = endDate.getTimeInMillis();
        int presumedDays = (int) ((endInstant - startDate.getTimeInMillis()) / MILLIS_IN_DAY);
        Calendar cursor = (Calendar) startDate.clone();
        cursor.add(Calendar.DAY_OF_YEAR, presumedDays);
        long instant = cursor.getTimeInMillis();
        if (instant == endInstant)
            return presumedDays;

        final int step = instant < endInstant ? 1 : -1;
        do {
            cursor.add(Calendar.DAY_OF_MONTH, step);
            presumedDays += step;
        } while (cursor.getTimeInMillis() != endInstant);

        if (negative) {
            presumedDays = -presumedDays;
        }

        return presumedDays;
    }
}

Related

  1. before(Calendar c, long offset)
  2. yearsBetweenDates(Calendar from, Calendar to)
  3. getExactDiff(final Calendar cal1, final Calendar cal2)