Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

localdate

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;
        }
    }
like image 578
PabloS Avatar asked Jan 18 '26 08:01

PabloS


2 Answers

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.

like image 112
Joop Eggen Avatar answered Jan 19 '26 20:01

Joop Eggen


Here is the test. You want to check if one of your dates is in the past. Your method works.

        LocalDate a = LocalDate.of(2010, 1, 10); // past
        LocalDate b = LocalDate.of(2030, 2, 10); // future
        System.out.println(isPast(a,b)); // prints true


         a = LocalDate.of(2030, 1, 10); // future
         b = LocalDate.of(2010, 2, 10); // past
         System.out.println(isPast(a,b)); // prints true

         a = LocalDate.of(2030, 1, 10);  // future
         b = LocalDate.of(2030, 2, 20);  // future
         System.out.println(isPast(a,b)); // prints false

         a = LocalDate.of(2010, 1, 10); // past
         b = LocalDate.of(2010, 2, 10); // past

         System.out.println(isPast(a,b)); // prints true

There may be granularity or timezone problems depending on how you specified the dates.

like image 38
WJS Avatar answered Jan 19 '26 20:01

WJS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!