gpt4 book ai didi

php - 在 PHP 中获取下周的日期

转载 作者:可可西里 更新时间:2023-11-01 13:13:21 26 4
gpt4 key购买 nike

我想回显下周的 Mo,Tu,We,Th,Fr,Sa,Su 的日期。

我的代码现在看起来像这样:

$date_monday = date("Y-m-d", strtotime('next monday'));
$date_tuesday = date("Y-m-d", strtotime('next tuesday'));
$date_wednesday = date("Y-m-d", strtotime('next wednesday'));
$date_thursday = date("Y-m-d", strtotime('next thursday'));
$date_friday = date("Y-m-d", strtotime('next friday'));
$date_saturday = date("Y-m-d", strtotime('next saturday'));
$date_sunday = date("Y-m-d", strtotime('next sunday'));

问题是,例如 sunday 的日期是错误的,因为下一个星期日是明天,但我想要下周星期日的日期。

有没有办法将 PHP 日期设置为星期日并计算新日期的天数?

最佳答案

这可以通过 DateTime 轻松实现类:

$dt = new DateTime();
// create DateTime object with current time

$dt->setISODate($dt->format('o'), $dt->format('W') + 1);
// set object to Monday on next week

$periods = new DatePeriod($dt, new DateInterval('P1D'), 6);
// get all 1day periods from Monday to +6 days

$days = iterator_to_array($periods);
// convert DatePeriod object to array

print_r($days);
// $days[0] is Monday, ..., $days[6] is Sunday
// to format selected date do: $days[1]->format('Y-m-d');

Demo

关于php - 在 PHP 中获取下周的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20162068/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com