Java LocalDate Between daysBetween(LocalDate firstDate, LocalDate secondDate)

Here you can find the source of daysBetween(LocalDate firstDate, LocalDate secondDate)

Description

Returns the number of days between two dates.

License

Open Source License

Parameter

Parameter Description
firstDate the first date
secondDate the second date, after the first

Return

the new date

Declaration

static long daysBetween(LocalDate firstDate, LocalDate secondDate) 

Method Source Code

//package com.java2s;
/**/*from  ww  w.  j  a  v a  2 s .c  om*/
 * Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
 * 
 * Please see distribution for license.
 */

import java.time.LocalDate;

public class Main {
    private static final int[] STANDARD = { 0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
    private static final int[] LEAP = { 0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 };

    /**
     * Returns the number of days between two dates.
     * <p>
     * Faster than the JDK method.
     * 
     * @param firstDate  the first date
     * @param secondDate  the second date, after the first
     * @return the new date
     */
    static long daysBetween(LocalDate firstDate, LocalDate secondDate) {
        int firstYear = firstDate.getYear();
        int secondYear = secondDate.getYear();
        if (firstYear == secondYear) {
            return doy(secondDate) - doy(firstDate);
        }
        if ((firstYear + 1) == secondYear) {
            return (firstDate.lengthOfYear() - doy(firstDate)) + doy(secondDate);
        }
        return secondDate.toEpochDay() - firstDate.toEpochDay();
    }

    /**
     * Finds the day-of-year of the date.
     * <p>
     * Faster than the JDK method.
     * 
     * @param date  the date to query
     * @return the day-of-year
     */
    static int doy(LocalDate date) {
        int[] lookup = (date.isLeapYear() ? LEAP : STANDARD);
        return lookup[date.getMonthValue()] + date.getDayOfMonth();
    }
}

Related

  1. daysBetween(LocalDate date1, LocalDate date2)
  2. getLocalDatesBetween(final LocalDate localDate1, final LocalDate localDate2)
  3. getRandomLocalDateBetween(int startYear, int endYear)
  4. isBetween(LocalDate date, LocalDate before, LocalDate after)
  5. isBetween13And18YearsBetween(LocalDate birthLocalDate, LocalDate now)