PHP Calculate number of working days/weekdays in daterange

A quick function to calculate the number of weekdays (Monday to Friday) in a given daterange:

function week_days($start, $end){
	$first_day = strtotime($start);
	$last_day = strtotime($end);
	if($first_day>$last_day){
		return 0;
	}else{
		$total_days = 0;
		$current_day = $first_day;
		
		while($current_day< =$last_day){
			$what_day = date('N',$current_day);
			if($what_day <= 5) { // 6 and 7 is Saturday and Sunday
			  $total_days++; // counter for total days
			}
			$current_day = $current_day + 86400; // +1 day in seconds
		}
		return $total_days;
	}
}

To use this function, pass the dates in the format “Y-m-d”, something like this:

$start = date('Y-m-01');
$end = date('Y-m-t');

$working_days =  week_days($start, $end);

echo $working_days;

Leave a Reply