Search code examples
javadatetimelocaldatedate-comparison

How do I subtract a localDate from another LocalDate


I am trying to calculate the number of days between 2 localDates

I am taking inspiration from this answer: https://stackoverflow.com/a/325964 to this question Determine Whether Two Date Ranges Overlap

The trouble is, this question uses dateTime which I believe is outdated, hence the reason for using localDate.

Does anyone know of a similar way to implement the algorithm in the above answer using localDate instead.

The minus method doesn't allow subtraction of another localDate.

I have tried using

ChoronoUnit.DAYS.between(LD1, LD2.plusDays(1)) //include the final day in the count

but there are occasions when this produces a negative number so the algorithm breaks because it chooses the smallest number as the number of days overlap


Solution

  • Andreas already gave the answer in a comment: you need to take the absolute value of the day difference first, then add 1 to make the count inclusive of both start and end date.

    public static long daysBetweenInclusive(LocalDate ld1, LocalDate ld2) {
        return Math.abs(ChronoUnit.DAYS.between(ld1, ld2)) + 1;
    }
    

    Let’s try it out:

        LocalDate ld1 = LocalDate.of(2020, Month.MAY, 4);
        System.out.println(daysBetweenInclusive(ld1, LocalDate.of(2020, Month.MAY, 2)));
        System.out.println(daysBetweenInclusive(ld1, ld1));
        System.out.println(daysBetweenInclusive(ld1, LocalDate.of(2020, Month.MAY, 7)));
    

    Output:

    3
    1
    4