PHP 日期 4 周前

我有以下代码20191027作为结果输出。


如果我修改第二行(即将时区设置为奥克兰),它会给我结果20191028。为什么是这样?


date_default_timezone_set("Europe/London");

#date_default_timezone_set("Pacific/Auckland");


$date_format =  'Ymd';


$day = "Sunday 4 week ago";

$start_of_the_week = strtotime($day);


$next_day = $start_of_the_week + (60 * 60 * 24 * 1);

$next_day = date($date_format, $next_day);


echo $next_day;

检查 2 个输出:


https://3v4l.org/A7ppT (20191027)

https://3v4l.org/Mfto3 (20191028)


千巷猫影
浏览 182回答 3
3回答

qq_遁去的一_1

在Europe/London时区...DST 于 2019 年 10 月 27 日星期日凌晨 02:00:00 结束,当地时钟向后拨 1 小时请记住,它strtotime在没有 DST 概念的 unix 时间戳上运行,但该date函数在格式化时会将 unix 时间戳调整为本地时区。所以:$start_of_the_week = strtotime("Sunday 4 week ago"); // $start_of_the_week is some unix timestampecho date("Y-m-d H:i:s", $start_of_the_week);        // 2019-10-27 00:00:00 Europe/London time$next_day = $start_of_the_week + (60 * 60 * 24 * 1); // you're adding 24 hours to a unix timestampecho date("Y-m-d H:i:s", $next_day);                 // 2019-10-27 23:00:00 Europe/London time而且2019-10-27 23:00:00还是一个星期天。解决方案是添加天数而不是小时数:$next_day = strtotime("+1 day", $start_of_the_week); // 2019-10-28 00:00:00

偶然的你

正如评论中所讨论的,问题是Europe/London在 4 周前的那一天完成夏令时,所以在那个时间加上 24 小时只会让你提前 23 小时。您可以通过使用DateTime对象并仅使用天数来避免此类问题:$date_format =  'Y-m-d H:i:s';$day = "Sunday 4 week ago";date_default_timezone_set("Europe/London");$date = new DateTime($day);$date->modify('+1 day');echo $date->format($date_format) . "\n";date_default_timezone_set("Pacific/Auckland");$date = new DateTime($day);$date->modify('+1 day');echo $date->format($date_format) . "\n";输出:2019-10-28 00:00:002019-10-28 00:00:003v4l.org 上的演示您也可以直接向DateTime构造函数指定时区:$date_format =  'Y-m-d H:i:s';$day = "Sunday 4 week ago";$date = new DateTime($day, new DateTimeZone("Europe/London"));$date->modify('+1 day');echo $date->format($date_format) . "\n";$date = new DateTime($day, new DateTimeZone("Pacific/Auckland"));$date->modify('+1 day');echo $date->format($date_format) . "\n";

翻翻过去那场雪

每个时区都有差异。例如“印度比美国华盛顿特区早 10 小时 30 分钟”。如果回显这些时区的时间,则最终会给出不同的结果。在您的情况下,“新西兰奥克兰比英国伦敦早 13 小时”,因此它给出了不同的 O/P希望这可以解决您对问题的回答:)
打开App,查看更多内容
随时随地看视频慕课网APP