For example, suppose today is Monday (2025-05-26), you want to subtract 3 working days. If you use it directly:
$date = new DateTime('2025-05-26');
$date->sub(new DateInterval('P3D')); // minus3sky
echo $date->format('Y-m-d');
The result is 2025-05-23 (Friday), which seems to be correct. But if the starting date is Monday and the working days you subtract are large, it will include Saturday and Sunday, and the calculation results will be deviated.
Cycle reduction days : For each day of reduction, first determine whether the day is a weekend (Saturday or Sunday).
Skip the weekend : If the day is a weekend, the reduction is not counted on the weekday reduction.
Continue to reduce the number of working days to meet the requirements .
Below is a sample function subtractWorkingDays , which starts with a specified date, subtracts the specified number of workdays, and skips weekends.
function subtractWorkingDays(DateTime $date, int $days): DateTime {
$result = clone $date; // Cloning avoids modifying the original object
while ($days > 0) {
$result->sub(new DateInterval('P1D')); // 每次减少一sky
$weekday = (int)$result->format('N'); // 1 (on Monday) arrive 7 (Sunday)
if ($weekday < 6) { // 只有on Mondayarrive周五才算作工作日
$days--;
}
}
return $result;
}
// Example of usage
$startDate = new DateTime('2025-05-26');
$workDaysToSubtract = 3;
$newDate = subtractWorkingDays($startDate, $workDaysToSubtract);
echo $newDate->format('Y-m-d'); // The output result is2025-05-21,Skip the weekend correctly
Use format('N') to get the week number, 1 is Monday and 7 is Sunday.
The $days count will only decrease when the day is a working day (1~5).
By looping, make sure that the number of days subtracted is purely working days.
When using date_sub directly to subtract the number of days, it may include weekends, resulting in business logic errors.
By cyclically determining whether it is a working day, and counting only decreases on the working day count, the requirement of subtracting the working day can be accurately achieved.
This method is simple and efficient, and is suitable for most scenarios that require working day calculations.