Skip to content

Core\Time\Date::year

$date->year(): int

Returns the year of a date, as an int.

2024-03-15 returns 2024. The year is the same number you give to Core\Time\Date::at, and the same number format prints with yyyy.

The result has the same name and type as the year option of with. So $date->with({ year: $date->year() + 1 }) gives the same day one year later. It throws a RuntimeError when that day does not exist, such as 29 February in a year that is not a leap year.

Good to know: use year when you need a number to calculate with. Use format when you need text to show.

Return value

Returns int. The year, from -9999 to 9999. The year before 1 is 0.

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 year

<?nvs
// Shows how to read the year of a date as a number.
var $invoice = Core\Time\Date::at(2024, 3, 15);
// `year` returns an `int`. This prints 2024.
echo $invoice->year(), "\n";
// You can calculate with it. This prints 2034, the year the invoice can be deleted.
echo $invoice->year() + 10, "\n";
Output
2024
2034

The age of a person

<?nvs
// Shows how to calculate the age of a person in whole years.
class Person
{
public static function age(Core\Time\Date $born, Core\Time\Date $today): int
{
int $years = $today->year() - $born->year();
// If this year's birthday has not come yet, the person is one year younger.
if ($today < $born->with({ year: $today->year() })) {
$years = $years - 1;
}
return $years;
}
}
var $born = Core\Time\Date::at(1990, 8, 20);
// The birthday in 2024 is on 20 August. This prints 33 and then 34.
echo Person::age($born, Core\Time\Date::at(2024, 8, 19)), "\n";
echo Person::age($born, Core\Time\Date::at(2024, 8, 20)), "\n";
Output
33
34

The same day next year

<?nvs
// Shows how to find the same day in the next year for a yearly contract.
var $signed = Core\Time\Date::at(2024, 9, 1);
// `with` replaces the year, and the month and the day stay the same. This prints 2025-09-01.
echo $signed->with({ year: $signed->year() + 1 })->format('yyyy-MM-dd'), "\n";
// 29 February 2025 does not exist, so `with` throws a `RuntimeError`.
var $leapDay = Core\Time\Date::at(2024, 2, 29);
try {
$leapDay->with({ year: $leapDay->year() + 1 });
} catch (RuntimeError $error) {
echo "2025-02-29 does not exist\n";
}
Output
2025-09-01
2025-02-29 does not exist