Core\Time\DateTime::daysInMonth
$dateTime->daysInMonth(): uintReturns the number of days in the month of this date and time, from 28 to 31.
February has 29 days in a leap year and 28 days in other years. The month is the month in the value's own time zone. One moment can be 31 January in London and 1 February in Berlin, so the result can depend on the time zone.
Use daysInMonth to find the last day of a month, for example for a bill that is due on the last day. with({ day: $dateTime->daysInMonth() }) gives that day.
Return value
Returns uint. 28 to 31. February has 29 days in a leap year.
Changelog
| Version | Change |
|---|---|
0.0.6 | A 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
Days in each month
<?nvs// Shows the number of days in the first four months of one year.
// `daysInMonth` returns the number of days in the month of the value.// This prints 31 for January, 28 for February, 31 for March and 30 for April.var $start = Core\Time\DateTime::fromIso('2026-01-15', 'UTC');int $month = 0;while ($month < 4) { var $day = $start->plus($month, Core\Unit::Month); echo $day->format('MMMM'), ': ', $day->daysInMonth(), "\n"; $month = $month + 1;}January: 31February: 28March: 31April: 30February in a leap year
<?nvs// Shows that February has 29 days in a leap year.
// 2024 is a leap year, so this prints 29.echo Core\Time\DateTime::fromIso('2024-02-10', 'UTC')->daysInMonth(), "\n";
// 2100 is not a leap year, because it ends in 00 and 400 does not divide it. This prints 28.echo Core\Time\DateTime::fromIso('2100-02-10', 'UTC')->daysInMonth(), "\n";
// The month is read in the value's own time zone.// 23:30 on 31 January in London is already 1 February in Berlin. This prints 31, then 29.var $london = Core\Time\DateTime::fromIso('2024-01-31 23:30', 'Europe/London');echo $london->daysInMonth(), "\n";echo $london->toInstant()->in(Core\Time\Zone::of('Europe/Berlin'))->daysInMonth(), "\n";29283129A payment on the last day
<?nvs// Finds the date of a monthly payment that a customer wants on the 31st of each month.
class Payment{ // A short month has no day 31. The payment is then on the last day of that month. public static function due(Core\Time\DateTime $month): string { uint $day = 31; if ($month->daysInMonth() < $day) { $day = $month->daysInMonth(); } return $month->with({ day: $day })->format('yyyy-MM-dd'); }}
// This prints 2026-01-31, 2026-02-28 and 2026-04-30.array<string> $months = ['2026-01-01', '2026-02-01', '2026-04-01'];foreach ($months as string $text) { echo Payment::due(Core\Time\DateTime::fromIso($text, 'UTC')), "\n";}2026-01-312026-02-282026-04-30