How can I calculate the number of Saturdays and Sundays between two dates in php?
Is there any inbuilt function for that purpose?
How can I calculate the number of Saturdays and Sundays between two dates in php?
Is there any inbuilt function for that purpose?
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, http://stackoverflow.com/questions/336127/calculate-business-days
You can use this to subtract from 7 to get the weekend days, or similar.
<?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).
there's definitely no built in function for that but you can use strtotime to loop days
$start = strtotime('2010-01-01');
$end = strtotime('2010-01-09');
function numWeekdays( $start_ts, $end_ts, $day, $include_start_end = false ) {
$day = strtolower( $day );
$current_ts = $start_ts;
// loop next $day until timestamp past $end_ts
while( $current_ts < $end_ts ) {
if( ( $current_ts = strtotime( 'next '.$day, $current_ts ) ) < $end_ts) {
$days++;
}
}
// include start/end days
if ( $include_start_end ) {
if ( strtolower( date( 'l', $start_ts ) ) == $day ) {
$days++;
}
if ( strtolower( date( 'l', $end_ts ) ) == $day ) {
$days++;
}
}
return (int)$days;
}
echo numWeekDays( $start, $end, 'saturday', false );