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:
I know it sounds a little vague, but I really don't know how to explain it different.
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.
<? 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')); } ?>
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!';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With