java localdate compare days code example

Example 1: java 8 datediff in days

LocalDate dateBefore;
LocalDate dateAfter;
long daysBetween = DAYS.between(dateBefore, dateAfter);

Example 2: java compare localdatetime

Using equals() LocalDate does override equals:

int compareTo0(LocalDate otherDate) {
    int cmp = (year - otherDate.year);
    if (cmp == 0) {
        cmp = (month - otherDate.month);
        if (cmp == 0) {
            cmp = (day - otherDate.day);
        }
    }
    return cmp;
}
If you are not happy with the result of equals(), you are good using the predefined methods of LocalDate.

isAfter()
isBefore()
isEqual()
Notice that all of those method are using the compareTo0() method and just check the cmp value. if you are still getting weird result (which you shouldn't), please attach an example of input and output

Example 3: java localdate subtract two dates

@Test
public void givenTwoDatesInJava8_whenDifferentiating_thenWeGetSix() {
    LocalDate now = LocalDate.now();
    LocalDate sixDaysBehind = now.minusDays(6);
 
    Period period = Period.between(now, sixDaysBehind);
    int diff = period.getDays();
 
    assertEquals(diff, 6);
}

Tags:

Java Example