PHP 日期 4 周前

PHP Date 4 Weeks Ago

我有以下代码,结果输出 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 个输出:

每个时区都有差异。

例如

"India is 10 hours and 30 minutes ahead of Washington, DC, USA"。如果回显这些时区的时间,最终会给出不同的结果。

在你的情况下 "Auckland, New Zealand is 13 hours ahead of London, UK",因此它给出了不同的 O/P

希望这能解决您对问题的回答:)

正如评论中所讨论的那样,问题在于 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:00
2019-10-28 00:00:00

Demo on 3v4l.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";

Demo on 3v4l.org

Europe/London时区...

DST ended on Sun 27-Oct-2019 at 02:00:00 A.M. when local clocks were set backward 1 hour

请记住,strtotime 在没有 DST 概念的 unix 时间戳上运行,但 date 函数在格式化时将 unix 时间戳调整为本地时区。所以:

$start_of_the_week = strtotime("Sunday 4 week ago"); // $start_of_the_week is some unix timestamp
echo 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 timestamp
echo 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