6

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.

2
  • 3
    I understand the question, you may want to convert all the times with the strtotime() function and start comparing. Maybe a DateTime object will help you here as well. Commented Jan 3, 2012 at 19:59
  • do you need to know if the range is within and the 3rd variable Commented Jan 3, 2012 at 20:10

3 Answers 3

7

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!';
}
Sign up to request clarification or add additional context in comments.

Comments

7

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.