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

本秂侑毒 提交于 2020-01-11 08:36:46

问题


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 2012-04-28 
$daterange2 = 2012-04-18 till 2012-05-01

Now, I'd like to know if daterange2 is within daterange1. But, as you can see, daterange2 only partly is within daterange1. Is there any way of getting 3 variables back, something like:

  1. 2012-04-18 till 2012-04-20
  2. 2012-04-20 till 2012-04-28
  3. 2012-04-28 till 2012-05-01

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


回答1:


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



回答2:


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.




回答3:


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!';
}
?>


来源:https://stackoverflow.com/questions/8717861/php-see-if-date-range-is-partly-within-another-date-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!