Core\Time\Date::weekday
$date->weekday(): Core\Time\WeekdayReturns the day of the week of a date, as a case of the Core\Time\Weekday enum.
The result is one of seven cases, from Core\Time\Weekday::Monday to Core\Time\Weekday::Sunday. You compare it with ==. A date has no time zone, so the result is the same everywhere.
as int converts the case to its position in the week, and Monday is 0. Saturday is 5 and Sunday is 6. So a date is a working day from Monday to Friday when this number is less than 5.
Good to know: to print the name of the day, use format with EEEE.
Return value
Returns Core\Time\Weekday. The Weekday case, Weekday::Monday through Weekday::Sunday.
Changelog
| Version | Change |
|---|---|
0.0.5 | Core\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 day of the week
<?nvs// Shows how to find the day of the week of a date.
var $holiday = Core\Time\Date::at(2024, 12, 25);
// `weekday` returns a case of the `Core\Time\Weekday` enum. This prints Wednesday.if ($holiday->weekday() == Core\Time\Weekday::Wednesday) { echo "Wednesday\n";}
// `as int` gives the position in the week, and Monday is 0. This prints 2.echo $holiday->weekday() as int, "\n";Wednesday2Working day or weekend
<?nvs// Shows how to check whether a date is a working day or on the weekend.
// Monday is 0 and Friday is 4, so a working day has a number less than 5.class Calendar{ public static function isWorkingDay(Core\Time\Date $date): bool { return ($date->weekday() as int) < 5; }}
// This prints one line for each day from Thursday 6 June to Monday 10 June 2024.var $day = Core\Time\Date::at(2024, 6, 6);int $shown = 0;while ($shown < 5) { echo $day->format('EEEE d MMMM'), ': ', Calendar::isWorkingDay($day) ? 'working day' : 'weekend', "\n"; $day = $day->plus(1, Core\Unit::Day); $shown = $shown + 1;}Thursday 6 June: working dayFriday 7 June: working daySaturday 8 June: weekendSunday 9 June: weekendMonday 10 June: working dayCount the working days in a month
<?nvs// Shows how to count the working days in a month.
// The loop starts on 1 May and stops when the date reaches June.var $day = Core\Time\Date::at(2024, 5, 1);int $working = 0;while ($day->month() == 5) { var $weekday = $day->weekday(); if ($weekday != Core\Time\Weekday::Saturday && $weekday != Core\Time\Weekday::Sunday) { $working = $working + 1; } $day = $day->plus(1, Core\Unit::Day);}
// May 2024 has 31 days, and 8 of them are on a weekend. This prints 23.echo $working, "\n";23