How can you add a specified number of weekdays to a given date in PHP?
To add a specified number of weekdays to a given date in PHP, you can loop through each day and check if it is a weekday (Monday to Friday). If it is a weekday, decrement the count of weekdays to add. Once the count reaches 0, return the final date.
function addWeekdaysToDate($date, $weekdaysToAdd) {
$currentDate = new DateTime($date);
while ($weekdaysToAdd > 0) {
$currentDate->modify('+1 day');
if ($currentDate->format('N') < 6) {
$weekdaysToAdd--;
}
}
return $currentDate->format('Y-m-d');
}
// Example usage
$date = '2022-01-10';
$weekdaysToAdd = 5;
$newDate = addWeekdaysToDate($date, $weekdaysToAdd);
echo $newDate; // Output: 2022-01-17
Related questions
-
PHP form submissions unique data values
-
Sorting Data Query
-
SQL injection user input validation prepared statements