Core\Time\Date::previous
$date->previous(Core\Time\Weekday $w): Core\Time\Date$date->previous( Core\Time\Weekday $w, ): Core\Time\Date
Returns the last date before this one that is on a given day of the week. You give the day as a case of Core\Time\Weekday, such as Weekday::Monday.
The result is one to seven days earlier. When the date is already on that weekday, previous returns the same weekday one week earlier. To include the date itself, call previous on the day after: $date->plus(1, Unit::Day)->previous(Weekday::Monday).
The result is a new Date, and the date you called it on does not change. previous throws a RuntimeError only when the result is before the year -9999.
Good to know: next finds the weekday after a date.
Parameters
$wCore\Time\WeekdayThe weekday to move to.
Return value
Returns Core\Time\Date. A new Date one to seven days earlier. It is seven days earlier when this date is already on $w.
Errors
RuntimeErrorThe result is before the year-9999.
Changelog
| Version | Change |
|---|---|
0.0.6 | Core\Time\Date::startOf and endOf return the first or last day of the date's week, month, quarter or year. difference counts whole days, weeks, months, quarters or years between two dates. next and previous find the nearest date on a given weekday. |
Examples
The last monday
<?nvs// Shows how to find the last Monday before a date.
use Core\Time\Weekday;
// 20 May 2026 is a Wednesday.var $today = Core\Time\Date::at(2026, 5, 20);
// The last Monday is two days earlier. This prints Mon 2026-05-18.echo $today->previous(Weekday::Monday)->format('EEE yyyy-MM-dd'), "\n";
// The last Friday is in the week before. This prints Fri 2026-05-15.echo $today->previous(Weekday::Friday)->format('EEE yyyy-MM-dd'), "\n";Mon 2026-05-18Fri 2026-05-15The same weekday
<?nvs// Shows what `previous` returns when the date is already on the weekday you give.
use Core\Time\Weekday;
// 20 May 2026 is a Wednesday.var $wednesday = Core\Time\Date::at(2026, 5, 20);
// `previous` always moves back, so the result is one week earlier. This prints 2026-05-13.echo $wednesday->previous(Weekday::Wednesday)->toIso(), "\n";
// To keep the date itself, start from the day after. This prints 2026-05-20.echo $wednesday->plus(1, Core\Unit::Day)->previous(Weekday::Wednesday)->toIso(), "\n";2026-05-132026-05-20The last friday of a month
<?nvs// Shows how to find the last Friday of a month, for example a pay day.
class Payroll{ // The function takes the first day of the next month and goes back to a Friday. public static function payDay(int $year, uint $month): Core\Time\Date { var $nextMonth = Core\Time\Date::at($year, $month, 1)->plus(1, Core\Unit::Month); return $nextMonth->previous(Core\Time\Weekday::Friday); }}
// This prints 2026-01-30, 2026-05-29 and 2026-07-31.echo Payroll::payDay(2026, 1)->toIso(), "\n";echo Payroll::payDay(2026, 5)->toIso(), "\n";echo Payroll::payDay(2026, 7)->toIso(), "\n";2026-01-302026-05-292026-07-31