Skip to content

Core\Time\DateTime::dayOfYear

$dateTime->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 a tip of the day.

Good to know: the count starts at 1.

Return value

Returns uint. 1 for 1 January through 365 or 366. It counts from one, as every other day count in this class does.

Examples

The number of a day in the year

<?nvs
// Shows how to get the number of a day within its year.
var $utc = Core\Time\Zone::UTC;
// `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\DateTime::fromIso('2024-01-01', $utc)->dayOfYear(), "\n";
echo Core\Time\DateTime::fromIso('2024-02-01', $utc)->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\DateTime::fromIso('2023-03-01', $utc)->dayOfYear(), "\n";
echo Core\Time\DateTime::fromIso('2024-03-01', $utc)->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.
// The number of days in a year is 366 in a leap year and 365 in other years.
class Year
{
public static function daysLeft(Core\Time\DateTime $day): uint
{
uint $length = 365;
if ($day->isLeapYear()) {
$length = 366;
}
return $length - $day->dayOfYear();
}
}
var $berlin = Core\Time\Zone::of('Europe/Berlin');
// 1 December 2024 is day 336 of 366. This prints 30.
echo Year::daysLeft(Core\Time\DateTime::fromIso('2024-12-01', $berlin)), "\n";
// On the last day of the year, the result is 0.
echo Year::daysLeft(Core\Time\DateTime::fromIso('2023-12-31 23:00', $berlin)), "\n";
Output
30
0

A tip for each day

<?nvs
// Shows how to pick a different tip of the day from a list, one after the other.
array<string> $tips = [
'Save your work often.',
'Use a password manager.',
'Check your backups.',
];
var $zone = Core\Time\Zone::of('America/New_York');
// The day number divided by the number of tips leaves a remainder of 0, 1 or 2.
// The remainder is the position of today's tip, so the tips repeat every three days.
var $day = Core\Time\DateTime::fromIso('2024-06-10', $zone);
int $shown = 0;
while ($shown < 4) {
int $position = ($day->dayOfYear() % 3) as int;
echo $day->format('d MMMM'), ': ', $tips[$position], "\n";
$day = $day->plus(1, Core\Unit::Day);
$shown = $shown + 1;
}
Output
10 June: Save your work often.
11 June: Use a password manager.
12 June: Check your backups.
13 June: Save your work often.