AMSOL e-Tutor

Tutorials, Code Samples for PHP, MySQL & Android

Get Working days for a date range in PHP


Example helps you to get working days falling between two dates.

PHP Code

$DFROM = '2020-01-01';
$DTO =  '2020-06-30';
$WD = 0;
	while (strtotime($DFROM) <= strtotime($DTO)) 
	{
		$DOW = date('w', strtotime($DFROM));
		if ($DOW < 5){$WD++; }
		$DFROM = date ("Y-m-d", strtotime("+1 day", strtotime($DFROM)));
	}
echo $WD;

Definition and Usage

$DFROM = '2020-01-01'; sets start date & saves in a variable

$DTO = '2020-06-30'; sets end date & saves in a variable

$WD = 0; declare & set WD variable to 0

while (strtotime($DFROM) <= strtotime($DTO)) { while loop starts to loop through complete date range

strtotime is a built in PHP function which Parses English textual datetimes into Unix timestamps

it will start the loop & continues doing so until end date reaches.

$DOW = date('w', strtotime($DFROM));

It gets numeric representation of the day (0 for Sunday, 6 for Saturday) & assigns the value to $DOW variable

if ($DOW < 5){$WD++; }

If statement evaluates the value & if it is less than 5 (working days) it increments the $DOW value

$DFROM = date ("Y-m-d", strtotime("+1 day", strtotime($DFROM))); }

Next line increases the date to re-start code execution to loop through further

echo $WD;

finally display the no of working stored in $WD variable

Code can be used as function given below


echo GetWorkingDays($DFROM, $DTO);

function GetWorkingDays($DFROM, $DTO)
{
	$WD = 0;
	while (strtotime($DFROM) <= strtotime($DTO)) 
	{
		$DOW = date('w', strtotime($DFROM));
		if ($DOW < 5){$WD++; }
		$DFROM = date ("Y-m-d", strtotime("+1 day", strtotime($DFROM)));
	}
	return $WD;
}

Related Study

Loop, While loop, if elseif else, strtotime function, date function, date reference