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

时间:2015-07-16 13:22:42

标签: php symfony

我正在尝试计算以下数组中日期之间的周末天数:

   $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)。

有人有任何想法吗?

3 个答案:

答案 0 :(得分:1)

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

$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
}

答案 1 :(得分:1)

首先,如果您正在完全按照书写方式定义数组,那么您将复制键,其中四个项将被覆盖。但假设我们只是看着对。将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;    
}   

可能有一个更优雅的解决方案。

答案 2 :(得分:1)

用于每对日期:

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;
}