PHP Weeks Between Two Dates: Handling Leap Years and Monday Iteration
Calculating the number of weeks between two dates is a straightforward arithmetic operation if you treat time as a continuous stream of seconds, but it becomes nuanced when you need to align those weeks to specific calendar boundaries like Mondays. The source requirement specifically asks for the count of full weeks and a list of every Monday date falling within a range, such as from July 10, 2009, to the present day, while strictly accounting for leap years and other calendar constraints.
In PHP, dates are not just strings; they are objects that carry significant metadata. Using DateTime or DateInterval is the modern approach, but naive implementations often fail when crossing year boundaries or ignoring leap seconds (though less common in business logic, they matter in high-precision systems). The core challenge here isn't just subtraction; it's normalization. A week is defined as seven days, but a calendar week starts on a Monday (in ISO standards) or Sunday (in US conventions). If you simply subtract two dates and divide by seven, you lose the granularity of which specific Mondays occurred.
To solve this robustly, you must first normalize your start date to the nearest preceding Monday. This establishes a consistent baseline. If your range starts on a Tuesday, that day does not count as a "Monday week," nor should it be included in your list of target dates. You then iterate forward by adding exactly 7 days (DateInterval with P1W) until you exceed the end date.
Here is a practical implementation pattern using PHP's native DateTime class, which handles leap years internally without requiring manual calculation logic:
$start = '2009-07-10';
$end = new DateTime('now');
$startObj = new DateTime($start);
// Normalize start date to the previous Monday to ensure we count full weeks starting on Monday
$startObj->modify('previous Monday');
$weekCount = 0;
$currentDate = clone $startObj;
while ($currentDate <= $end) {
echo "Monday: " . $currentDate->format('Y-m-d') . "\n";
// Increment week count and move date forward by 7 days
$currentDate->modify('+1 week');
}
This snippet addresses the leap year constraint automatically. PHP's DateTime class adjusts for February 29th in leap years seamlessly when calculating intervals, so you do not need to write custom logic to check if a year is divisible by four (with the exception of century rules). Attempting to calculate this using raw string manipulation or integer math often leads to off-by-one errors near year boundaries.
A critical trade-off arises when defining what constitutes a "week." If your business logic requires ISO-8601 weeks (where week 1 is the first week containing a Thursday), you must ensure your start date aligns with that specific definition. The previous Monday adjustment forces alignment to calendar weeks, which might differ slightly from ISO-week numbering if your range begins in late December of a non-leap year versus early January of a leap year.
For larger applications, iterating one week at a time is memory-efficient but computationally slower than necessary for very long ranges. If you are processing millions of records, calculating the total number of weeks via integer division (diff->days / 7) provides an O(1) solution, while generating the list of Mondays requires O(n) iteration. You must choose based on whether you need the aggregate count or the granular list.
If you are building a Laravel application, leveraging the Eloquent date helpers can simplify this further, though the underlying PHP DateTime logic remains the same. For complex scheduling systems where precision regarding leap seconds or specific timezone offsets is required, always ensure your DateTimeZone is explicitly set to avoid discrepancies between server time and user local time.
For further guidance on advanced date manipulation patterns within the Laravel ecosystem, you can refer to resources like https://laravelcompany.com.