从php数组中计算范围日期之间的周末天数


Count weekend days between range dates from array in php

我想从下面的数组中计算日期之间的周末天数:

   $dates[] = array ( 'DateFrom' => '2015-07-10', 'DateTo' => '2015-07-10', 'DateFrom' => '2015-07-12', 'DateTo' => '2015-07-12', 'DateFrom'=> '2015-07-17', 'DateTo'=> '2015-07-19') ;

结果必须返回这些日期之间的周末天数在这些日期之间有3天的周末(2015-07-12、2015-07-18和2015-07-19)。

有人知道吗?

您需要从开始日期到结束日期进行循环,并且在每次迭代中需要检查日期(sat/sun)算法:

$weekends = 0;
$startDate = strtotime($startDate);
$endDate = strtotime($endDate);
while($startDate<$endDate) {
//"N" gives ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0) 
 $day = date("N",$startDate);
 if($day == 6 || $day == 7) {
  $weekends++;
} 
$startDate = 24*60*60 ; //1 day
}

首先,如果您完全按照写入的方式定义数组,那么您就复制了键,其中四个项将被覆盖。但是假设我们只看成对。将每对中的FromDate和ToDate传递给该函数,并将所有返回值相加。

function getWeekends ($fromDate, $toDate) {
    $from = strtotime($fromDate);
    $to = strtotime($toDate);
    $diff = floor(abs($to-$from)/(60*60*24));    // total days betwixt
    $num  = floor($diff/7) * 2;              // number of weeks * 2
    $fromNum = date("N", $from);
    $toNum = date("N", $to);
    if ($toNum < $fromNum)
       $toNum += 7;
    // get range of day numbers
    $dayarr = range($fromNum, $toNum); 
    // check if there are any weekdays in that range 
    $num += count(array_intersect($dayarr, array(6, 7, 13)));
    return $num;    
}   

可能有更优雅的解决方案

用于每对日期:

function getWeekendDays($startDate, $endDate)
{    
    $weekendDays = array(6, 7);
    $period = new DatePeriod(
        new DateTime($startDate),
        new DateInterval('P1D'),
        new DateTime($endDate)
    );
    $weekendDaysCount = 0;
    foreach ($period as $day) {
        if (in_array($day->format('N'), $weekendDays)) {
            $weekendDaysCount++;
        }
    }
    return $weekendDaysCount;
}