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

Asked

Viewed 243 times

0

I am building a system in php to check if a given time interval has conflicting dates with another time interval. It is possible to do this?

Example:

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

  • It would be good to explain the question better with examples.

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

  • In the case of the example, it would be conflicting, it is not?

  • Yeah, that’s right

  • Are the dates conflicting only if one period is completely within the other? Or are they confiltantes if only a part of a period is within another period? For example, 10/05/2017 until 05/15/2017 and 05/12/2017 until 05/16/2017, are also conflicting?

  • The dates are conflicting if a single part of one period is within the other as well

Show 1 more comment

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, soon the break $dt1_1 -> $dt1_2 is contained in the interval $dt2_1 -> $dt2_2.


Example when it is phony:

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)? NAY

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";
}

Obs.: The replaces on the dates are necessary: "To avoid potential ambiguity, it’s best to use ISO 8601 (YYYY-MM-DD) Dates or Datetime::createFromFormat() when possible."

Test in Ideone.

  • Very good your answer. Solved my problem. Thank you!

  • @felipebrum ( ° ʖ °) Obg!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.