The Best Way to Get the First and Last Day of Last Month
When building reporting dashboards or aggregating data for SQL queries, you often need precise date ranges. A common requirement is retrieving the first and last day of the previous month. Developers frequently encounter a specific snippet used to solve this: constructing a timestamp with mktime, formatting it with date, and manually adjusting the month and year components.
While the approach provided in many discussions uses mktime to build a raw Unix timestamp, then formats it back into a string, there is a more robust and readable alternative available in modern PHP environments: DateTimeImmutable. This method eliminates the need for manual arithmetic on dates and years, significantly reducing the chance of off-by-one errors when handling year boundaries.
The Manual Approach vs. DateTime
The snippet often seen in older codebases or quick scripts looks like this:
$month_ini = date("Y-m-d", mktime(0, 0, 0, date("m", strtotime("-1 month")), 1, date("Y", strtotime("-1 month"))));
$month_end = date("Y-m-d", mktime(0, 0, 0, date("m", strtotime("-1 month")), date("t", strtotime("-1 month")), date("Y", strtotime("-1 month"))));
This code works, but it relies on mktime to create a timestamp based on a calculated month. The logic is sound: it grabs the current month, subtracts one, and explicitly sets the day to 1 for the start and the number of days in that month (date('t')) for the end. However, this method separates the date logic into multiple steps. You are effectively calculating the year, extracting the month, and then recombining them. If you ever need to handle timezones differently or switch between different date formats mid-calculation, this manual reconstruction becomes brittle.
The DateTimeImmutable Solution
A cleaner implementation uses DateTimeImmutable. This class handles all the heavy lifting regarding calendar rules, including leap years and varying month lengths. Here is how you can refactor the logic:
$lastMonth = (new DateTime())->modify('-1 month');
$firstDay = $lastMonth->format('Y-m-d');
$lastDay = clone $lastMonth;
$lastDay->modify('last day of this month'); // or '-1 day' depending on context, but simpler logic follows below
Actually, the most direct way to get the last day is slightly different. We calculate the first day of next month and subtract one day, or we use the format method with a specific modifier. A very concise pattern looks like this:
$today = new DateTimeImmutable();
$lastMonthStart = $today->modify('first day of last month');
$lastMonthEnd = $today->modify('last day of last month');
$start = $lastMonthStart->format('Y-m-d');
$end = $lastMonthEnd->format('Y-m-d');
This approach is declarative. You tell the object what you want ("first day of last month") rather than calculating the components yourself. It also automatically handles the transition from December to January or February to March without any extra code to check for year rollovers.
Integration with SQL Queries
The primary goal mentioned in the source material is feeding these dates into SQL queries for stats. Depending on your database, you might want ISO date strings (YYYY-MM-DD) or a range format (YYYY-MM-01 to YYYY-MM-DD). The DateTimeImmutable objects formatted as 'Y-m-d' provide exactly that standard ISO 8601 format, which is universally accepted by MySQL, PostgreSQL, and SQLite.
When constructing the query string in PHP, you can directly interpolate these variables:
$query = "SELECT * FROM logs WHERE created_at BETWEEN ? AND ?";
$stmt = $pdo->prepare($query);
$stmt->execute([$start, $end]);
Using prepared statements with these calculated dates ensures that special characters or format issues do not leak into the query execution. This is significantly safer than concatenating strings directly, especially if you ever decide to change the date format dynamically.
Trade-offs and Limitations
The main trade-off between the mktime approach and DateTimeImmutable is dependency on PHP versions. While DateTime has been standard for a long time, DateTimeImmutable was introduced in PHP 5.5. If you are maintaining legacy systems running older PHP versions, the manual calculation might be the only viable option. However, even in those cases, using DateTime (mutable) is generally preferred over mktime because it separates concerns clearly and allows for chaining methods like format, modify, and add.
Another consideration is timezone handling. The code snippets above assume UTC or the system default timezone. If your application stores dates in a specific timezone, you should ensure your DateTimeImmutable instance is instantiated with that timezone context before performing calculations. For example, (new DateTimeImmutable('now', new DateTimeZone('America/New_York'))) ensures all subsequent math operates within that local time frame, preventing accidental UTC offsets in your SQL results.
Ultimately, while the mktime trick works, adopting a dedicated date-time class aligns with modern PHP best practices. It reduces cognitive load, makes the code self-documenting, and simplifies the maintenance of complex reporting logic.