How can the PHP date function be used to accurately calculate the calendar week for dates that straddle two different years?

When calculating the calendar week for dates that straddle two different years, we need to take into account the ISO-8601 standard for week numbering. We can use the PHP date function along with the "W" format character to accurately determine the calendar week. By checking if the week number belongs to the previous or next year, we can handle dates that span across two years.

function getCalendarWeek($date) {
    $week = date('W', strtotime($date));
    $year = date('Y', strtotime($date));
    
    // Check if the week belongs to the previous year
    if ($week == 1 && date('n', strtotime($date)) == 12) {
        $year--;
    }
    
    // Check if the week belongs to the next year
    if ($week >= 52 && date('n', strtotime($date)) == 1) {
        $year++;
    }
    
    return $year . '-W' . $week;
}

// Example usage
$date = '2021-12-31';
echo getCalendarWeek($date); // Output: 2021-W52