For an object oriented approach you can use DateTime('Sunday')::add()
with a DateInterval
of "PxD"
When using the standard Numeric representation of the day of the week DateTime::format('w')
as 0-6
for Sun-Sat or ISO-8601 numeric representation of the day of the week DateTime::format('N')
as 1-7
for Mon-Sun.
https://3v4l.org/3uthm
$weekday = (new DateTime('Sunday'))
->add(new DateInterval('P' . $dow . 'D'));
The ISO-8601 representation works as expected since it uses Sunday + 7 days (Sunday)
, resulting in Sunday + 1 day (Monday)
and Sunday + 6 days (Saturday)
.
Alternatively replace Sunday for Monday and use $dowISO - 1
https://3v4l.org/5uLOL
$weekdayISO = (new DateTime('Monday'))
->add(new DateInterval('P' . ($dowISO - 1) . 'D'));
DatePeriod Example
https://3v4l.org/uG9NT
$sunday = new DateTimeImmutable('Sunday');
$monday = new DateTimeImmutable('Monday');
foreach (new DatePeriod($sunday, new DateInterval('P1D'), 6) as $date) {
$dow = $date->format('w');
$weekday = $sunday->add(new DateInterval('P' . $dow . 'D'));
$dowISO = $date->format('N');
$weekdayISOM = $monday->add(new DateInterval('P' . ($dowISO - 1) . 'D'));
$weekdayISOS = $sunday->add(new DateInterval('P' . $dowISO . 'D'));
printf("STD: %s = %s\nISOM: %s = %s\nISOS: %s = %s\n\n",
$dow, $weekday->format('l'),
$dowISO, $weekdayISOM->format('l'),
$dowISO, $weekdayISOS->format('l')
);
}
Results
STD: 0 = Sunday
ISOM: 7 = Sunday
ISOS: 7 = Sunday
STD: 1 = Monday
ISOM: 1 = Monday
ISOS: 1 = Monday
STD: 2 = Tuesday
ISOM: 2 = Tuesday
ISOS: 2 = Tuesday
STD: 3 = Wednesday
ISOM: 3 = Wednesday
ISOS: 3 = Wednesday
STD: 4 = Thursday
ISOM: 4 = Thursday
ISOS: 4 = Thursday
STD: 5 = Friday
ISOM: 5 = Friday
ISOS: 5 = Friday
STD: 6 = Saturday
ISOM: 6 = Saturday
ISOS: 6 = Saturday