What are common pitfalls when calculating the difference between two dates in PHP, especially when excluding weekends?

When calculating the difference between two dates in PHP and excluding weekends, a common pitfall is not accounting for weekends when subtracting the days. To solve this, you can loop through each day between the two dates and check if it's a weekend day (Saturday or Sunday) before incrementing the total days difference.

function getWeekdayDifference($startDate, $endDate) {
    $start = new DateTime($startDate);
    $end = new DateTime($endDate);
    $interval = DateInterval::createFromDateString('1 day');
    $period = new DatePeriod($start, $interval, $end);

    $weekendDays = [6, 7]; // Saturday and Sunday
    $difference = 0;

    foreach ($period as $date) {
        if (!in_array($date->format('N'), $weekendDays)) {
            $difference++;
        }
    }

    return $difference;
}

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