PHP, see if date range is partly within another date range

后端 未结 3 511
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-18 10:43

I\'ve been looking forever for this, but the answer seems nowhere. Here\'s the problem:

Say, I\'ve got two date ranges.

$daterange1 = 2012-04-20 till         


        
相关标签:
3条回答
  • 2021-01-18 11:19

    Here's an example using PHP's DateTime class. Note that if you pass an invalid date string to DateTime::__construct() the function will throw an exception, so you should implement a try/catch block if you're worried about this. Also, I use PHP's min and max functions so that it doesn't matter which order the dates are specified.

    $daterange1 = array('2012-04-20', '2012-04-28');
    $daterange2 = array('2012-04-18', '2012-05-01');
    
    $range_min = new DateTime(min($daterange1));
    $range_max = new DateTime(max($daterange1));
    
    $start = new DateTime(min($daterange2));
    $end = new DateTime(max($daterange2));
    
    if ($start >= $range_min && $end <= $range_max) {
      echo 'woot!';
    } else {
      echo 'doh!';
    }
    
    0 讨论(0)
  • 2021-01-18 11:31

    Though this is a very old post. But still if someone stuck. Here's complete example for overlapping dates.

    <?php
    $daterange1 = array('2017-09-24', '2017-09-28');
    $daterange2 = array('2017-09-22', '2017-09-25');
    
    $range_min = new DateTime(min($daterange1));
    $range_max = new DateTime(max($daterange1));
    
    $start = new DateTime(min($daterange2));
    $end = new DateTime(max($daterange2));
    
    if ($start >= $range_min && $end <= $range_max) {
    echo 'Overlapping!';
    } 
    else if($end > $range_min && $start < $range_max){
    echo "partialy";
    }
    else {
    echo 'free!';
    }
    ?>
    
    0 讨论(0)
  • 2021-01-18 11:39

    Well, logically you can break down the requirements for a range to be partly in another.

    A range is only partly within another range if:

    • range1's start date is > than range2's start date but not > than range2's end date
    • range1's end date is < than range2's end date but not < than range2's start date

    If either or both of those are true then the ranges are within each other.

    0 讨论(0)
提交回复
热议问题