Finding the Last Day of a Month in PHP
Finding the number of days in a month is useful for reporting, billing periods, scheduling, and date validation. PHP can do this directly with its date APIs, including support for leap years.
A Simple getLastDay Function
The following function accepts a month in YYYY-MM format and returns the number of days in that month:
function getLastDay(string $month): int
{
$date = new DateTimeImmutable($month . '-01');
return (int) $date->format('t');
}How the Code Works
-
Create a date for the first day of the month
$date = new DateTimeImmutable($month . '-01');For an input such as
"2022-06", this creates a date representing June 1, 2022. -
Read the number of days in the month
return (int) $date->format('t');The
tformat character returns the number of days in the represented month, from 28 through 31.
Usage Examples
echo getLastDay("2022-01"); // 31
echo getLastDay("2022-02"); // 28
echo getLastDay("2024-02"); // 29
echo getLastDay("2022-04"); // 30
PHP handles leap years automatically, so February 2024 correctly reports 29 days.
Alternative with date()
If you are already working with Unix timestamps, the t format character also works with date():
$timestamp = strtotime('2024-02-01');
echo date('t', $timestamp); // 29
Conclusion
PHP’s t date format makes it easy to determine the number of days in a month without manually maintaining month-length or leap-year rules. DateTimeImmutable is a clear choice when your application already works with PHP date objects.