How to check if a time interval has conflicting dates with another time interval in php?

0

I'm building a system in php to check if a certain time interval has dates conflicting with another time interval. Is it possible to do this?

Example:

I have two date ranges: 05/10/2017 until 05/15/2017; and 4/18/2017 to 10/23/2017. I want to know how to check if the first range is contained within the second range.

    
asked by anonymous 04.11.2017 / 18:29

1 answer

0

You can do a very simple check:

($dt1_1 <= $dt2_2) && ($dt1_2 >= $dt2_1)

Explanation:

  10/05      15/05
    [- $dt1_x -]
  [--------------- $dt2_x ---------------]
18/04                                  23/10
  • $dt1_1 (10/05) is less than or equal to $dt2_2 (23/10)? yes
  • $dt1_2 (15/05) is greater than or equal to $dt2_1 (18/04)? yes

Both conditions are true , so the $dt1_1 -> $dt1_2 interval is contained in the $dt2_1 -> $dt2_2 range.

Example when false :

10/05      15/05
  [- $dt1_x -]
              [----------- $dt2_x ------------]
            16/05                           23/10
  • $dt1_1 (10/05) is less than or equal to $dt2_2 (23/10)? yes
  • $dt1_2 (15/05) is greater than or equal to $dt2_1 (16/05)? NOT

Code:

$dt1_1 = date("Y-m-d", strtotime(str_replace("/","-","10/05/2017")));
$dt1_2 = date("Y-m-d", strtotime(str_replace("/","-","15/05/2017")));
$dt2_1 = date("Y-m-d", strtotime(str_replace("/","-","18/04/2017")));
$dt2_2 = date("Y-m-d", strtotime(str_replace("/","-","23/10/2017")));

if(($dt1_1 <= $dt2_2) && ($dt1_2 >= $dt2_1)){
    echo "True";
}else{
    echo "False";
}

Note: The replaces on dates are required: " #

Try Ideone .

    
04.11.2017 / 19:25