Core\Time\DateTime::year
$dateTime->year(): intReturns the year of a date and time, as an int.
The year is read in the time zone of the value. One moment can be in two different years in two zones. At 23:30 UTC on 31 December 2024, year returns 2024 in London and 2025 in Berlin.
The result has the same name and type as the year option of with. So $d->with({ year: $d->year() + 1 }) gives the same date and time one year later. It throws a RuntimeError when that date does not exist, such as 29 February in a year that is not a leap year.
Good to know: to read the year in another zone, first convert the value with toInstant()->in($zone).
Return value
Returns int. The year, from -9999 to 9999. The year before 1 is 0.
Changelog
| Version | Change |
|---|---|
0.0.5 | Core\Time\DateTime::year, Core\Time\DateTime::month, Core\Time\DateTime::day, Core\Time\DateTime::hour, Core\Time\DateTime::minute, Core\Time\DateTime::second and Core\Time\DateTime::nanoseconds return the parts of a date and time as numbers. Each one reads the clock in the zone of the value. Core\Time\DateTime::year returns an int, and the others return a uint. |
Examples
Read the year
<?nvs// Shows how to read the year of a date and time as a number.
var $order = Core\Time\DateTime::fromIso('2024-03-15 10:00', 'Europe/Berlin');
// `year` returns an `int`. This prints 2024.echo $order->year(), "\n";
// You can calculate with it. This prints 2031, the last year the order must be kept.echo $order->year() + 7, "\n";20242031New year in two zones
<?nvs// Shows that the same moment can be in a different year in two time zones.
var $moment = Core\Time\Instant::fromIso('2024-12-31T23:30:00Z');
// In London it is still 31 December. This prints 2024.echo $moment->in('Europe/London')->year(), "\n";
// Berlin is one hour ahead, so it is already 1 January. This prints 2025.echo $moment->in('Europe/Berlin')->year(), "\n";20242025Renew a yearly plan
<?nvs// Shows how to find the renewal date of a plan that runs for one year.
var $started = Core\Time\DateTime::fromIso('2024-05-20 14:05', 'America/Chicago');
// `with` replaces the year. The month, the day and the time stay the same.// This prints 2025-05-20 14:05.var $renews = $started->with({ year: $started->year() + 1 });echo $renews->format('yyyy-MM-dd HH:mm'), "\n";2025-05-20 14:05