我有以下代码作为结果输出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个输出:
答案 0 :(得分:3)
在Europe/London
时区...
DST已于2019年10月27日上午02:00结束。当当地时钟 向后设置1小时
请记住,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
答案 1 :(得分:1)
如评论中所述,问题在于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
您也可以直接向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";
答案 2 :(得分:0)
每个时区之间都有差异。
例如
“印度比美国华盛顿特区早10小时30分钟”。如果回显这些时区的时间,则会以不同的结果结束。
在您的案例中,“新西兰奥克兰比英国伦敦早13小时”,因此它给出了不同的O / P。
希望这可以解决您对问题的回答:)