I am trying to make a function which checks if 2 date periods overlap. For example:
1 July 2019 - 5th July 2019
and 2nd July 2019 - 4th July 2019
would return true
as the 2 date periods overlap
1 July 2019 - 5th July 2019
and 13th July 2019 - 24th July 2019
would return false
as the 2 date periods don't overlap
I get the wrong answer when I compare these 2 dates 24 March 2019 - 27 March 2019
and 27 March 2019 - 29 March 2019
. I get the answer false
. Though the answer should be true
because I count all days inclusive.
How can I fix this?
import java.time.LocalDate;
import java.time.Month;
public class TestClass {
public static void main(String[] args) {
LocalDate start1 = LocalDate.of(2019, Month.MARCH, 24);
LocalDate end1 = LocalDate.of(2019, Month.MARCH, 27);
LocalDate start2 = LocalDate.of(2019, Month.MARCH, 27);
LocalDate end2 = LocalDate.of(2019, Month.MARCH, 29);
boolean ans = dateOverlaps(start1, end1, start2, end2);
System.out.println(ans);
}
public static boolean dateOverlaps(LocalDate start1, LocalDate end1, LocalDate start2, LocalDate end2) {
return start2.isBefore(end1) && end2.isAfter(start1);
}
}
Aucun commentaire:
Enregistrer un commentaire