PHP, see If the date range is partially within another date range

I have always looked for this, but the answer seems nowhere. Here's the problem:

Say I have two date ranges.

$daterange1 = 2012-04-20 till 2012-04-28 $daterange2 = 2012-04-18 till 2012-05-01 

Now I would like to know if daterange2 is within daterange1. But, as you can see, daterange2 is only partially within daterange1. Is there a way to return 3 variables, for example:

  • 2012-04-18 to 2012-04-20
  • 2012-04-20 - 2012-04-28
  • 2012-04-28 to 2012-05-01

I know this sounds a little vague, but I really don't know how to explain it differently.

+6
source share
3 answers

Here is an example using the PHP 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 are worried about this. In addition, I use the PHP functions min and max , so it doesn't matter in which order the dates are listed.

 $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!'; } 
+7
source

Well, logically you can violate the range requirements to be partially in another.

A range is only partially within another range if:

  • range1 start date → than start date2, but not> than end date2.
  • range1 end date is <than the end date of range2, but not <than the start date2.

If one or both of them is true, the ranges are inside each other.

+5
source

Although this is a very old post. But anyway, if someone is stuck. Here is a complete example of date overlapping.

 <?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
source

Source: https://habr.com/ru/post/905014/


All Articles