Alex Rivera | Logout

Calculating the number of Saturdays and Sundays

Asked 2010-06-02T14:34:01.080
10

How can I calculate the number of Saturdays and Sundays between two dates in php?

Is there any inbuilt function for that purpose?

Edit
Report

1 Answer

0
<?php
date_default_timezone_set("Europe/Lisbon");
$d1 = new DateTime("2009-06-01"); /* inclusive */
$d2 = new DateTime("2009-07-01"); /* exclusive */

$interval = $d2->diff($d1);
$number_of_days = $interval->format("%d");

$number_of_weekends = $number_of_days / 7;
$remainder = $number_of_days % 7;

if ($remainder >=2 && $d1->format("D") == "Sat")
    $number_of_weekends++;
elseif ($d1->format("w") + $remainder >= 8)
    $number_of_weekends++;

I may have missed by one in the last condition, be sure to check it with different starting dates. (Feel free to edit this answer if you spot an error).

answered 2010-06-02T14:58:26.770

Your Answer