PHP Get Last Day of Given Month
A common requirement in date manipulation is determining the boundaries of a specific month. You might need to generate invoices spanning a calendar period, validate subscription durations, or simply log data by month. When using PHP's DateTime functions, the logic seems straightforward: set the day to the 1st for the start and use a dynamic token for the end.
Consider this snippet where the goal is to output the first and last days of February 2015:
$month = '02';
$first_day_this_month = date('Y-' . $month . '-01');
$last_day_this_month = date('Y-' . $month . '-t');
echo $first_day_this_month;
echo '<->';
echo $last_day_this_month;
This code produces 2015-02-01<->2015-02-31. The output is incorrect because February 2015 has only 28 days. The developer expects 2015-02-01<->2015-02-28, but the logic behind $last_day_this_month appears to be broken.
The root cause lies in how PHP interprets the -t token within the date() function when constructing a date string from scratch rather than modifying an existing DateTime object. The date() function relies on the current system time and applies format modifiers to that context. When you provide a partial date like Y-m-t, PHP attempts to parse it against the current timestamp. If the month provided is not the current one, or if the year doesn't match the system's current year in specific edge cases involving leap years and formatting, the behavior can become unpredictable or fall back to defaults that don't respect the intended month's length.
However, a more robust and predictable approach exists that avoids these parsing ambiguities entirely: using DateTime objects with explicit modification methods. This method separates the creation of the date object from the retrieval of the formatted string, ensuring the logic is applied correctly regardless of the current system time.
To fix the issue, create a DateTime instance for the first day of the target month, then use the built-in lastDay() method to calculate the final date:
$month = '02'; // Target month
$year = (int) date('Y'); // Or pass a specific year if needed
// Create an object representing the 1st day of the target month
$start = new DateTime("$year-$month-01");
// Use lastDay() to get the actual last day of that month
$end = clone $start;
$end->modify('last day');
echo $start->format('Y-m-d') . '<->' . $end->format('Y-m-d');
This approach yields 2015-02-01<->2015-02-28 as expected. The DateTime::lastDay() method internally handles the complexity of varying month lengths, including leap years for February. It guarantees that you never receive a date like March 31st when asked for the last day of a non-leap year's February.
Another viable alternative involves using the format('t') modifier on a valid DateTime object. While date('Y-m-t') often fails in direct string construction scenarios, modifying an existing object works reliably:
$targetMonth = '02';
$targetYear = date('Y'); // Adjust as necessary
$start = new DateTime("$targetYear-$targetMonth-01");
$end = (clone $start)->format('Y-m-t', true); // Not standard, but logic holds with modify()
// More direct usage with format modifier on the object:
$endFormatted = $start->modify('last day')->format('Y-m-d');
The trade-off here is readability versus brevity. The date() one-liner is concise but brittle when dealing with non-current months or years in string manipulation contexts. The DateTime object approach, while slightly more verbose, offers explicit control and correctness. It prevents subtle bugs where the system date interferes with your intended calculation logic.
In production environments using frameworks like Laravel, you might find yourself needing this logic within a controller or service. While Laravel provides helper methods like Carbon, which simplifies this even further via $date->month($month)->year($year)->lastOfMonth()->format('Y-m-d'), understanding the underlying PHP mechanics ensures you can solve the problem even outside the framework's helpers.
When building date calculators, always prioritize object-oriented manipulation over raw string formatting when the target date is not now. This pattern eliminates the ambiguity of format modifiers and ensures consistent behavior across different server timezones and system dates.