Calculating the number of Saturdays and Sundays

I don't think there is a built in for that, but this should do the job :

$startTime = START_TIMESTAMP;
$endTime = END_TIMESTAMP;
$time = $startTime;
$count = 0;

while(date('w', $time) != 0) { // 0 (for Sunday) through 6 (for Saturday)
    $time += 86400;
}

while($time < $endTime) {
    $count++;
    $time += 7 * 86400;
}

There is a related question here already, Calculate business days

You can use this to subtract from 7 to get the weekend days, or similar.


You can calculate it mathematically like this - Based on Roland's Answer

private function getNumberOfWeekendDays(\DateTimeInterface $startDate, \DateTimeInterface $endDate): int
{
    $startNumber = (int) $startDate->format('N');
    $endNumber = (int) $endDate->format('N');
    $daysBetweenStartAndEnd = $endDate->diff($startDate)->d;

    $weekendDays = (int) (2 * ($daysBetweenStartAndEnd + $startNumber) / 7);
    $weekendDays = $weekendDays - ($startNumber == 7 ? 1 : 0) - ($endNumber == 7 ?  1 :  0);

    return $weekendDays;
}

Let us all KISS (Keep It Simple Stupid). Why make it so complicated?

function countWeekendDays($start, $end)
{
    // $start in timestamp
        // $end in timestamp


    $iter = 24*60*60; // whole day in seconds
    $count = 0; // keep a count of Sats & Suns

    for($i = $start; $i <= $end; $i=$i+$iter)
    {
        if(Date('D',$i) == 'Sat' || Date('D',$i) == 'Sun')
        {
            $count++;
        }
    }
    return $count;
   }

Tags:

Php

Date