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;
}
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With