Test if a range intersects another range of numbers

前端 未结 6 1464
小鲜肉
小鲜肉 2021-01-07 03:41

I have 2 range of numbers:

  • $startTime to $endTime
  • $offerStartTime to $offerEndTime

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-07 04:05

    If you are just checking whether any part of the offer overlaps any part of the range, it's simple.

    if ($offerStartTime < $endTime && $offerEndTime > $startTime)  {
        echo 'The ranges overlap';
    }
    

    Here's a picture representing all the possibilities of overlap and non-overlap to visualize why this works.

    Based on your inputs and expected false outputs, I used < and >. If you wanted to also include ranges that intersected at a point, you would need to use <= and >= instead.

提交回复
热议问题