如果采用面向对象的方法,您可以使用DateTime('Sunday')::add()
和DateInterval
"PxD"
当使用标准数字表示星期几的方式时,DateTime::format('w')
将星期日至星期六表示为0-6
,或者使用ISO-8601数字表示星期几的方式,DateTime::format('N')
将星期一至星期日表示为1-7
。
https://3v4l.org/3uthm
$weekday = (new DateTime('Sunday'))
->add(new DateInterval('P' . $dow . 'D'));
ISO-8601表示法按预期工作,因为它使用星期日+7天(星期日)
,结果是星期日+1天(星期一)
和星期日+6天(星期六)
。
或者将星期日替换为星期一,并使用$dowISO - 1
https://3v4l.org/5uLOL
$weekdayISO = (new DateTime('Monday'))
->add(new DateInterval('P' . ($dowISO - 1) . 'D'));
DatePeriod 示例
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')
);
}
结果
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
date('l')
(小写 L)获取完整的星期几名称。更多信息 - ᴍᴇʜᴏᴠ