简体   繁体   中英

Count weekend days between range dates from array in php

I'm trying to calculate the number of weekend days between dates from the array below:

   $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') ;

The result must return number of weekend days between these dates Between these dates are 3 days of weekend (2015-07-12, 2015-07-18, and 2015-07-19).

Anyone have any idea?

You need to loop through from start date to end date and in each iteration need to check for day (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
}

Firstly, if you're defining your array exactly as written, you're duplicating keys and four of those items will be overwritten. But assuming we're just looking at the pairs. Pass the FromDate and ToDate from each pair to this function and add up all the return values.

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

There may be a more elegant solution.

To be used on each pair of dates:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM