Java Calendar Between daysBetween(Calendar early, Calendar late)

Here you can find the source of daysBetween(Calendar early, Calendar late)

Description

Returns the days between two dates.

License

Open Source License

Parameter

Parameter Description
early a parameter
late a parameter

Return

the days between two dates.

Declaration

public static final int daysBetween(Calendar early, Calendar late) 

Method Source Code

//package com.java2s;

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

public class Main {
    /**//www  .ja  v a2  s .c  o m
     * Returns the days between two dates. Positive values indicate that
     * the second date is after the first, and negative values indicate, well,
     * the opposite. Relying on specific times is problematic.
     *
     * @param early the "first date"
     * @param late the "second date"
     * @return the days between the two dates
     */
    public static final int daysBetween(Date early, Date late) {

        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        c1.setTime(early);
        c2.setTime(late);

        return daysBetween(c1, c2);
    }

    /**
     * Returns the days between two dates. Positive values indicate that
     * the second date is after the first, and negative values indicate, well,
     * the opposite.
     *
     * @param early
     * @param late
     * @return the days between two dates.
     */
    public static final int daysBetween(Calendar early, Calendar late) {

        return (int) (toJulian(late) - toJulian(early));
    }

    /**
     * Return a Julian date based on the input parameter. This is
     * based from calculations found at
     * <a href="http://quasar.as.utexas.edu/BillInfo/JulianDatesG.html">Julian Day Calculations
     * (Gregorian Calendar)</a>, provided by Bill Jeffrys.
     * @param c a calendar instance
     * @return the julian day number
     */
    public static final float toJulian(Calendar c) {

        int Y = c.get(Calendar.YEAR);
        int M = c.get(Calendar.MONTH);
        int D = c.get(Calendar.DATE);
        int A = Y / 100;
        int B = A / 4;
        int C = 2 - A + B;
        float E = (int) (365.25f * (Y + 4716));
        float F = (int) (30.6001f * (M + 1));
        float JD = C + D + E + F - 1524.5f;

        return JD;
    }

    public static final float toJulian(Date date) {

        Calendar c = Calendar.getInstance();
        c.setTime(date);

        return toJulian(c);
    }
}

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)