Defining "Last Week" in PHP: Handling Edge Cases and Time Zones
Determining the date range for "last week" is a deceptively simple task that often trips up developers because the definition of a week varies depending on your requirements. In the example provided, where today is 2014-2-8 and the desired range is 2014-1-26 ~ 2014-2-1, the logic relies on specific boundaries: the Monday preceding the current week and the Sunday of that week. If your application treats Sunday as the start of a business week, these dates shift entirely. Without explicit definitions, you risk returning data for the wrong period.
The core challenge lies in calculating the offset correctly. A naive approach might simply subtract seven days from today, but that yields "last week" relative to the current day, not necessarily the specific calendar week requested. To replicate the logic in your function, you must first identify the start of the current week (usually Monday) and then move back one full week.
Here is a robust implementation using DateTime objects, which handle date arithmetic more safely than raw string manipulation:
function getLastWeekRange($startDate = '2014-02-08') {
$today = new DateTime($startDate);
// Find the Monday of the current week
$currentMonday = (clone $today)->modify('this monday');
// Subtract 7 days to get the Monday of last week
$lastWeekMonday = (clone $currentMonday)->modify('-7 days');
// Calculate the Sunday of last week by adding 6 days
$lastWeekSunday = (clone $lastWeekMonday)->modify('+6 days');
return [
'start' => $lastWeekMonday->format('Y-m-d'),
'end' => $lastWeekSunday->format('Y-m-d')
];
}
This approach ensures that regardless of what day today is, you always capture the full 7-day block defined by Monday through Sunday. If you need to exclude the current week entirely and strictly target the previous calendar interval, you might instead subtract seven days from the very first day of the current month or year, depending on your business logic.
The Pitfall of Time Zones
One critical detail often overlooked in date calculations is the server's time zone. PHP's date_default_timezone_get() returns the system's configured timezone. If your application runs in UTC but displays dates in a local timezone like America/New_York, your "today" calculation could shift by several hours, potentially pushing a midnight boundary into yesterday or tomorrow.
For example, if it is 11:00 PM on Monday in New York, subtracting one day might yield Sunday night in UTC (which is technically still Monday). Always ensure you are operating in the correct timezone context before performing arithmetic. You can set this explicitly within your function or at the application startup to guarantee consistency across different environments.
Leveraging Laravel for Reusability
If you are building a larger application using the Laravel framework, you do not need to write these functions from scratch every time. Laravel provides a powerful Carbon interface that wraps DateTime and offers fluent methods for date manipulation.
Instead of writing custom logic to calculate offsets, you can utilize Carbon's built-in helpers:
use Carbon\Carbon;
$lastWeek = Carbon::now();
// Get the Monday of last week
$start = $lastWeek->startOfWeek()->subWeek();
// Get the Sunday of last week
$end = $start->addDays(6);
echo $start->format('Y-m-d') . ' ~ ' . $end->format('Y-m-d');
This abstraction reduces boilerplate code and minimizes the risk of off-by-one errors. It also handles leap years and daylight saving time transitions automatically, provided your timezone is configured correctly. If you are working on a project where date logic is critical, consider exploring community packages like spatie/laravel-permission or similar tools that often include date range utilities, though standard Carbon methods usually suffice for basic ranges.
Final Considerations
When implementing this logic, always validate your output against known dates to ensure the "Monday-Sunday" assumption matches your database schema. If your system treats Saturday as the start of the week, you must adjust the startOfWeek() modifier accordingly. The goal is not just to get a date string, but to ensure that every query generated from these dates returns the exact business period your users expect.