Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 767
user1128582 Avatar asked Jan 03 '12 19:01

user1128582


People also ask

How do you check if a DateTime is in a range?

Datetime objects are comparable, so you can compare datetime objects using the < , > , <= , >= , and == comparison operators. Therefore, you can use the expression start <= current <= end to check if a current time falls into the interval [start, end] when assuming that start , end , and current are datetime objects.

How can I limit date in PHP?

<? php $start_date = new DateTime('2011-05-15'); $end_date = new DateTime('2011-07-30'); while($end_date > $start_date) { echo $start_date->format('Y-m-d') . "\n"; $start_date->add(new DateInterval('P1D')); } ?>


1 Answers

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!';
}
like image 167
rdlowrey Avatar answered Oct 02 '22 06:10

rdlowrey