Skip to content

Core\Time\Date::dayOfYear

$date->dayOfYear(): uint

Returns the number of the day within its year, where 1 January is day 1.

The result is from 1 to 365, or from 1 to 366 in a leap year. 1 February is day 32. After February the number depends on the year: 1 March is day 60 in 2023 and day 61 in 2024.

Use it to count the days that have passed in a year, or the days that are left. It is also a simple way to pick one item from a list for each day, such as the person on duty.

Good to know: the count starts at 1.

Return value

Returns uint. 1 for 1 January, up to 365, or 366 in a leap year.

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

The number of a day in the year

<?nvs
// Shows how to get the number of a day within its year.
// `dayOfYear` counts from 1, so 1 January is day 1 and 1 February is day 32.
// This prints 1 and then 32.
echo Core\Time\Date::at(2024, 1, 1)->dayOfYear(), "\n";
echo Core\Time\Date::at(2024, 2, 1)->dayOfYear(), "\n";
// 2024 is a leap year, so 1 March is one day later than in 2023.
// This prints 60 and then 61.
echo Core\Time\Date::at(2023, 3, 1)->dayOfYear(), "\n";
echo Core\Time\Date::at(2024, 3, 1)->dayOfYear(), "\n";
Output
1
32
60
61

Days left in the year

<?nvs
// Shows how to work out how many days are left in the year.
// A leap year has 366 days, and other years have 365.
class Year
{
public static function daysLeft(Core\Time\Date $date): uint
{
uint $length = 365;
if ($date->isLeapYear()) {
$length = 366;
}
return $length - $date->dayOfYear();
}
}
// 1 December 2024 is day 336 of 366. This prints 30.
echo Year::daysLeft(Core\Time\Date::at(2024, 12, 1)), "\n";
// On the last day of the year, the result is 0.
echo Year::daysLeft(Core\Time\Date::at(2023, 12, 31)), "\n";
Output
30
0

The person on duty

<?nvs
// Shows how to choose the person on duty for each day from a list.
array<string> $team = ['Ana', 'Ben', 'Chen'];
// The day number divided by 3 leaves a remainder of 0, 1 or 2.
// The remainder is the position in the list, so the names repeat every three days.
var $day = Core\Time\Date::at(2024, 3, 30);
int $shown = 0;
while ($shown < 4) {
int $position = ($day->dayOfYear() % 3) as int;
echo $day->format('d MMMM'), ': ', $team[$position], "\n";
$day = $day->plus(1, Core\Unit::Day);
$shown = $shown + 1;
}
Output
30 March: Ana
31 March: Ben
1 April: Chen
2 April: Ana