Search code examples
javalocaldate

How do I check if two LocalDates are in the past?


I am currently programming error avoidance. So I have two LocalDates: from and until and I want to check if one of them is in the past.

This is my method. But somewhere there seems to be an error, because if I select a LocalDate for "from" which is in the past, I get a false back.

    private static boolean isPast(LocalDate from, LocalDate until) {
        if (LocalDate.now().isAfter(from) || LocalDate.now().isAfter(until)) {
            return true;
        } else {
            return false;
        }
    }

Solution

  • Alternatively you could write:

    private static boolean atLeastOneInThePast(LocalDate from, LocalDate until) {
        LocalDate today = LocalDate.now();
        return today.isAfter(from) || today.isAfter(until);
    }
    

    Which is 23:59 consistent. And allows an easy debugging of today.

    Your code seems fine, if from is yesterday. So only your system clock, LocalDate.now(), may be off.