Calculating Week Ranges in PHP: A Robust Approach to ISO Weeks
Deriving the start and end dates of a specific week solely from a year and week number is a deceptively complex task. The ambiguity usually stems from the definition of "Monday." Does Monday count as week one, or does Sunday? Furthermore, does week 1 always contain January 4th, or can it shift based on the calendar year's configuration? If you attempt to solve this using simple arithmetic or naive date manipulation, you will quickly encounter edge cases where your logic breaks down.
To solve this reliably, you must adhere to the ISO-8601 standard. Under ISO-8601, a week number is strictly defined by its Monday, which must also be the first day of that week. Consequently, the start date of any given week is always a Monday. The challenge lies in correctly identifying which year contains that specific Monday.
The most robust method to achieve this involves using PHP's DateTime and DateInterval classes rather than manual calculations. Manual calculation requires complex conditional logic to handle years where January 1st falls on a Friday, Saturday, or Sunday (which belong to the last week of the previous year) versus those where it falls on Monday, Tuesday, Wednesday, Thursday, or Sunday (where week one is shorter).
Here is a practical implementation that calculates the range for any given $year and $week:
function getStartAndEndDate($year, $week) {
// Create a DateTime object for the first day of the given year
$firstDayOfYear = new DateTime("$year-01-01");
// Get the day of the week of January 1st (1=Monday, 7=Sunday)
$dayOfWeek = (int)$firstDayOfYear->format('N');
// Calculate how many days to add to reach the start of Week 1
// ISO-8601 Week 1 is the week containing the first Thursday of the year.
// Alternatively, it's the week where Monday >= Jan 4th.
// A simpler heuristic: The first week is the one containing Jan 4.
// We create a date for Jan 4th to determine the anchor point
$anchorDay = new DateTime("$year-01-04");
// Calculate days difference between Jan 1st and Jan 4th
$interval = $anchorDay->diff($firstDayOfYear);
$daysDiff = $interval->days;
// The start of week 1 is Monday.
// If Jan 1 was a Sunday (7), Jan 4 is Wednesday (3). We need to go back to previous Monday.
// Actually, the standard way is: Start date = Jan 1st + (DayOfWeek - 1) days to get to previous Sunday? No.
// Let's use a cleaner logic based on the ISO week date calculation formula.
// The number of days between Jan 4th and the target Monday determines the offset from Jan 1.
// Create a dummy object for Week 1 Monday
// We know Week 1 starts on the Monday containing Jan 4.
// If Jan 1 is Monday (1), Jan 4 is Thursday. Start = Jan 1.
// If Jan 1 is Tuesday (2), Jan 4 is Friday. Start = Jan 1 - 0 days? No, start is previous Monday?
// Wait, if Jan 1 is Tue, then the week containing Jan 4 starts on Monday Dec 31 prev year.
// Correct Logic:
// Calculate the day of the week for Jan 4th.
$jan4 = new DateTime("$year-01-04");
$dayOfWeekJan4 = (int)$jan4->format('N'); // 1=Mon ... 7=Sun
// The start of the year's first ISO week is the Monday of the week containing Jan 4.
// If Jan 4 is Mon (1), start is Jan 1.
// If Jan 4 is Tue (2), start is Dec 31 prev year.
// Formula: Start Date = Jan 4 - (DayOfWeekJan4 - 1) days.
$startOfFirstWeek = new DateTime($jan4->format('Y-m-d'));
$intervalToMonday = new DateInterval("P{$daysDiff}D"); // This logic above was slightly flawed, let's fix.
// Refined Logic:
// 1. Jan 4th always belongs to ISO Week 1.
// 2. Find the Monday of that week.
$target = new DateTime("$year-01-04");
$daysToMonday = ($target->format('N') - 1);
if ($daysToMonday < 0) {
$daysToMonday += 7;
}
// Actually, simpler: Jan 4 is always in week 1. The start of week 1 is the Monday before or on Jan 4.
$startOfWeek1 = (clone $target)->modify("-" . ($target->format('N') - 1) . " days");
// Now we have the absolute Monday of Week 1 for this year.
// To get the start of any week N, we simply add (N-1) weeks to this anchor.
$anchorDate = new DateTime($startOfWeek1->format('Y-m-d'));
$weeksToAdd = ($week - 1);
$interval = new DateInterval("P" . ($weeksToAdd * 7) . "D");
$startDate = (clone $anchorDate)->add($interval);
// The end date of the week is the Sunday following that Monday.
$endDate = (clone $startDate)->modify('+6 days');
// Format as requested: Y-n-j (Year, Month without leading zero, Day without leading zero)
return [
$startDate->format('Y-n-j'),
$endDate->format('Y-n-j')
];
}
// Example usage:
// getStartAndEndDate(2023, 1)
This approach avoids the pitfalls of trying to calculate leap years manually or guessing the day of the week. By anchoring on January 4thâa date guaranteed to fall within ISO Week 1âyou establish a reliable baseline for every year. From there, simple interval arithmetic handles the rest.
It is worth noting that formatting dates without leading zeros (Y-n-j) can be slightly verbose in standard PHP functions, but it is easily handled by the format() method as shown above. If you are building a larger application where date handling is frequent, consider encapsulating this logic within a service class or using Laravel's Carbon facade, which handles these ISO calculations with even less boilerplate code.
