找出日期范围内有多少个周末

时间:2015-11-23 09:45:39

标签: php

例如,我有两个日期2015-10-282015-12-31。从这些我想知道在给定的日期范围内有多少个星期六和星期日。我可以找到那些日期之间的差异,但我找不到多少个周末。

是谁做过这个?

这是我目前的代码:

function createDateRange($maxDate, $cell, $lead, $offArray = array()){
    $dates = [];
    --$cell;
    --$lead;

    $edate = date('Y-m-d', strtotime($maxDate." -$lead day"));
    $sdate = date('Y-m-d', strtotime($edate." -$cell day"));

    $start = new DateTime($sdate);
    $end = new DateTime($edate);
    $end = $end->modify('+1 day');
    $interval = DateInterval::createFromDateString('1 day');
    $period = new DatePeriod($start, $interval, $end);

    foreach($period as $d){
        $dt = $d->format('Y-m-d');
        if(!in_array($dt, $dates)){
            $dates[] = $dt;
        }
    }

    return $dates;
}

基本上我想将sat + sun计数添加到日期范围。

1 个答案:

答案 0 :(得分:0)

使用此功能:

function getDateForSpecificDayBetweenDates($startDate, $endDate, $weekdayNumber)
{
    $startDate = strtotime($startDate);
    $endDate = strtotime($endDate);

    $dateArr = array();

    do
    {
        if(date("w", $startDate) != $weekdayNumber)
        {
            $startDate += (24 * 3600); // add 1 day
        }
    } while(date("w", $startDate) != $weekdayNumber);


    while($startDate <= $endDate)
    {
        $dateArr[] = date('Y-m-d', $startDate);
        $startDate += (7 * 24 * 3600); // add 7 days
    }

    return($dateArr);
}

函数调用获取2015年所有星期日的日期:

$dateArr = getDateForSpecificDayBetweenDates('2015-01-01', '2015-12-31', 0);

print "<pre>";
print_r($dateArr);