Skip to content

Core\Time\Date::daysInMonth

$date->daysInMonth(): uint

Returns the number of days in the month of a date, from 28 to 31.

February has 29 days in a leap year and 28 days in other years. The result depends only on the year and the month, so every day of a month gives the same number.

Use it to loop over every day of a month, or to share a monthly amount over its days. The result is a uint, and daysInMonth never throws an error.

Good to know: endOf(Unit::Month) returns the last day of the month as a Date.

Return value

Returns uint. 28 to 31. February has 29 days in a leap year.

Changelog

VersionChange
0.0.6A Date and a DateTime return four more calendar parts. daysInMonth() is the number of days in the month, and quarter() is 1 to 4. isoWeek() and isoWeekYear() are the week number and its year in ISO 8601, where a week starts on Monday.

Examples

The length of each month

<?nvs
// Shows the number of days in each month of 2026.
uint $month = 1;
while ($month <= 12) {
var $first = Core\Time\Date::at(2026, $month, 1);
// `daysInMonth` returns 28, 30 or 31 for the months of 2026.
echo $first->format('MMMM'), ': ', $first->daysInMonth(), "\n";
$month = $month + 1;
}
Output
January: 31
February: 28
March: 31
April: 30
May: 31
June: 30
July: 31
August: 31
September: 30
October: 31
November: 30
December: 31

February in a leap year

<?nvs
// Shows that February is one day longer in a leap year.
// 2024 is a leap year. This prints 29.
echo Core\Time\Date::at(2024, 2, 1)->daysInMonth(), "\n";
// 2023 is not a leap year. This prints 28.
echo Core\Time\Date::at(2023, 2, 1)->daysInMonth(), "\n";
// Every day of the month gives the same number. This prints 29.
echo Core\Time\Date::at(2024, 2, 29)->daysInMonth(), "\n";
Output
29
28
29

A daily budget

<?nvs
// Shows how to share a monthly budget of 3000 over the days of the month.
class Budget
{
// The function divides the budget by the number of days in the month.
// `Core\Math::quotient` returns the whole number part of the division.
public static function perDay(int $monthly, Core\Time\Date $date): int
{
return Core\Math::quotient($monthly, $date->daysInMonth() as int);
}
}
// This prints 100 for April, 96 for May and 103 for February 2024.
echo Budget::perDay(3000, Core\Time\Date::at(2026, 4, 10)), "\n";
echo Budget::perDay(3000, Core\Time\Date::at(2026, 5, 10)), "\n";
echo Budget::perDay(3000, Core\Time\Date::at(2024, 2, 10)), "\n";
Output
100
96
103