How can brute-force methods be avoided when calculating date differences in PHP, especially when dealing with weekends?

When calculating date differences in PHP, especially when dealing with weekends, brute-force methods can be avoided by utilizing PHP's built-in date and time functions. One approach is to calculate the total number of days between two dates, then subtract the number of weekends (Saturdays and Sundays) within that range. This can be achieved by iterating through each day in the range and checking if it falls on a weekend day.

function getBusinessDays($startDate, $endDate) {
    $start = new DateTime($startDate);
    $end = new DateTime($endDate);
    
    $interval = new DateInterval('P1D');
    $dateRange = new DatePeriod($start, $interval, $end);

    $businessDays = 0;
    foreach ($dateRange as $date) {
        $dayOfWeek = $date->format('N');
        if ($dayOfWeek < 6) {
            $businessDays++;
        }
    }

    return $businessDays;
}

// Example usage
$startDate = '2022-01-01';
$endDate = '2022-01-10';
echo getBusinessDays($startDate, $endDate); // Output: 6