How do I find common dates/days in two date ranges
I want to find out common days/dates
between two periods
.
For example
period1: 25-10-2010 to 25-11-2010
period2: 10-11-2010 to 10-12-201开发者_如何转开发0
Here 15 days
, 10-11
to 25-11
are common. How can I find it in PHP or Zend Framework.
Using NullUserException's suggested method
date_default_timezone_set('GMT');
$period1 = array('25-10-2010','25-11-2010');
$period2 = array('10-11-2010','10-12-2010');
$p1 = range(strtotime($period1[0]),strtotime($period1[1]),86400);
$p2 = range(strtotime($period2[0]),strtotime($period2[1]),86400);
$r = array_intersect($p1,$p2);
foreach($r as $date) {
echo $date,' - ',date('d-M-Y H:i:s',$date),'<br />';
}
$nb_days = (strtotime($period1[1])-strtotime($period2[0])) / 86400
Should work.
See this SO answer for more info: https://stackoverflow.com/a/2970328/781153
And the corresponding code in PHP:
$period1 = ['25-10-2010', '25-11-2010'];
$period2 = ['10-11-2010', '10-12-2010'];
$dates = [
'p1start' => new DateTime($period1[0]),
'p1end' => new DateTime($period1[1]),
'p2start' => new DateTime($period2[0]),
'p2end' => new DateTime($period2[1])
];
$start = max($dates['p1start'], $dates['p2start']);
$end = min($dates['p1end'], $dates['p2end']);
$days = $start->diff($end);
var_dump($days);
Result:
object(DateInterval)[694]
[...]
public 'invert' => int 0
public 'days' => int 15
[...]
Note that the invert
property may be 1
, if there's no common days. A solution to get zero days when there's no overlap would be:
$commonDays = $start > $end ? 0 : $start->diff($end)->days;
精彩评论