What functions in PHP can be used for date calculations while considering weekends?
When performing date calculations in PHP while considering weekends, we need to account for skipping over Saturdays and Sundays. One way to do this is by using the `DateTime` class along with the `modify()` method to skip weekends when adding or subtracting days from a date.
function addWeekdaysToDate($date, $days) {
$dateObj = new DateTime($date);
while ($days > 0) {
$dateObj->modify('+1 day');
if ($dateObj->format('N') < 6) {
$days--;
}
}
return $dateObj->format('Y-m-d');
}
// Example usage
$date = '2022-01-10';
$daysToAdd = 5;
$newDate = addWeekdaysToDate($date, $daysToAdd);
echo $newDate; // Output: 2022-01-17
Related Questions
- How can one ensure that custom scripts and configurations in the htaccess file are compatible with a PHP update?
- In what scenarios is it advisable to save uploaded files before displaying them in PHP forms?
- How can PHP be used to calculate the number of days a user has had a specific team in an online league?