Skip to content

Core\Time\Date::month

$date->month(): uint

Returns the month of a date, as a uint from 1 to 12.

January is 1 and December is 12. 2024-03-15 returns 3. To print the name of the month, use format with MMMM.

The result has the same name and type as the month option of with. So $date->with({ month: $date->month() + 1 }) gives the same day in the next month. It throws a RuntimeError when that day does not exist. plus with Core\Unit::Month gives the last day of the month in that case.

Good to know: month 13 does not exist, so with also throws an error for a date in December.

Return value

Returns uint. The month, from 1 for January to 12 for December.

Changelog

VersionChange
0.0.5Core\Time\Date::year, Core\Time\Date::month and Core\Time\Date::day return the parts of a date as numbers. Core\Time\Date::weekday returns a Core\Time\Weekday case, and Core\Time\Date::dayOfYear returns the day of the year from 1. Core\Time\Date::isLeapYear checks if the year is a leap year.

Examples

Read the month

<?nvs
// Shows how to read the month of a date as a number.
var $order = Core\Time\Date::at(2024, 3, 15);
// `month` returns a `uint`, and January is 1. This prints 3.
echo $order->month(), "\n";
// `format` with `MMMM` prints the name of the month. This prints March.
echo $order->format('MMMM'), "\n";
// `with` takes the same number. This prints 2024-04-15.
echo $order->with({ month: $order->month() + 1 })->format('yyyy-MM-dd'), "\n";
Output
3
March
2024-04-15

The quarter of a date

<?nvs
// Shows how to find the quarter of the year that a date is in.
// Months 1 to 3 are the first quarter, 4 to 6 the second, and so on.
class Report
{
public static function quarter(Core\Time\Date $date): uint
{
uint $month = $date->month();
if ($month <= 3) {
return 1;
}
if ($month <= 6) {
return 2;
}
if ($month <= 9) {
return 3;
}
return 4;
}
}
// This prints Q1, Q2 and Q4.
echo 'Q', Report::quarter(Core\Time\Date::at(2024, 2, 10)), "\n";
echo 'Q', Report::quarter(Core\Time\Date::at(2024, 6, 30)), "\n";
echo 'Q', Report::quarter(Core\Time\Date::at(2024, 11, 5)), "\n";
Output
Q1
Q2
Q4

Summer prices

<?nvs
// Shows how to choose a hotel price from the month of the stay.
// A night in June, July or August costs 120. A night in any other month costs 80.
class Hotel
{
public static function nightPrice(Core\Time\Date $night): int
{
uint $month = $night->month();
if ($month >= 6 && $month <= 8) {
return 120;
}
return 80;
}
}
// A stay of four nights, from 30 May to 2 June 2024. This prints 400.
var $night = Core\Time\Date::at(2024, 5, 30);
int $total = 0;
int $nights = 0;
while ($nights < 4) {
$total = $total + Hotel::nightPrice($night);
$night = $night->plus(1, Core\Unit::Day);
$nights = $nights + 1;
}
echo $total, "\n";
Output
400