newbieCoder
newbieCoder

Reputation: 33

How can I efficiently check if date ranges don't overlap?

So basically what I'm looking for is a better way to prevent dates from overlapping each other. So if I already have created, let us say, an event between 10.09.2016 to 15.09.2016, the next event I create can't be between these two dates.

This code here is what I have so far, but I think it's messy and I'm not even quite sure that it works properly.

(fromDate.isAfter(element.getFromDate()) && fromDate.isBefore(element.getToDate()) || toDate.isAfter(element.getFromDate()) && toDate.isBefore(element.getToDate()) || fromDate.isBefore(element.getFromDate()) && toDate.isAfter(element.getToDate()) || fromDate.isEqual(element.getFromDate()) && toDate.isEqual(element.getToDate()) || fromDate.isBefore(element.getFromDate()) && toDate.isEqual(element.getToDate()) || fromDate.isEqual(element.getFromDate()) && toDate.isAfter(element.getToDate()))

I'm using java.time.LocalDate

Upvotes: 0

Views: 92

Answers (1)

Marc B
Marc B

Reputation: 360702

That is messy, and can be greatly simplified. Here's all the possibilities for two date ranges to overlap. call them 'a,b' and 'x,y':

              x     y      
        -------------------
        a  b                    no overlap
                      a b       no overlap

                a b             full overlap
        a                b      full overlap
        a     b                 partial   (b = x)
        a        b              partial 
        a           b           partial   (b = y)
        a                b      partial
              a          b      partial   (a = x)
                 a       b      partial
                    a    b      partial   (a = y)

Since you're interested only in the overlap cases, you can simply reverse the logic and check for NO overlap, which boils down to:

if (!((b < x) || (a > y)))

Upvotes: 5

Related Questions