strtotime与时区不同


strtotime is different with timezone

似乎我不太了解函数strtotime。我的情况是,我想将当前时间(现在)与特定时区上的特定时间进行比较

例如,特定时间为"美国/纽约"时区的"本周一14:00:00":

 $specificTime  = strtotime("monday this week 14:00:00 America/New_York");

我当前的代码是:

 $now  = strtotime("now America/New_York");
 if ($now > $specificTime) {
     //do something
 }

但我发现上面的$now比当前时间提前了6个小时。我猜数字6来自美国/纽约的05:00偏移量,加上1小时的夏令时。

它应该将时区从$now中删除,它将正常工作:

 $now  = strtotime("now");
 if ($now > $specificTime) {
     //do something
 }

有人能解释一下为什么strtotime("now America/New_York")strtotime("now)领先6个小时,为什么它们不相等吗?真的很困惑。

p.S:我在格林尼治标准时间+07:00。

简单调试:

<?php
$now  = strtotime("now America/New_York");
echo date('r', $now);
// Thu, 28 Nov 2013 16:39:51 +0100

显示这样的命令正在执行:

  1. 计算我默认时区的本地时间(10:39:51+0100)
  2. 返回对应于纽约时间10:39:51的时间戳(-0500)

用字符串进行日期操作非常复杂。想象一下,你试着用字符串函数strtofloat('one plus square root of half hundred')做数学运算——会有很大的错误空间。因此,我的建议是保持简单,只有在有一些好处时才与简单表达式一起使用,例如strtotime('+1 day')

如果您需要使用不同的时区,我建议您使用适当的DateTime对象。如果您选择使用Unix时间戳,请忘记时区:Unix时间戳根本没有时区信息。

您可以为此使用DateTime。我认为在strtotime中设置时区是无效的。

$specificTime = new DateTime("monday this week 14:00:00", new DateTimeZone("America/New_York")));
$now = new DateTime("now", new DateTimeZone("America/New_York"));

然后,您可以将unix时间戳与以下内容进行比较:

if ($now->getTimestamp() > $specificTime->getTimestamp()) {
    // do something ...
}

每个时区之间都有时间偏移。

strtotime()函数将根据时区返回Unix时间戳。

它将使用默认时区,除非在该参数中指定了时区。

默认时区为date_default_timezone_get()的返回值;

查看下面的代码:

<?php
// UTC
echo date_default_timezone_get(), "'n";
// 2013-11-28 14:41:37
echo date('Y-m-d H:i:s', strtotime("now America/New_York")), "'n";
// 2013-11-28 09:41:37
echo date('Y-m-d H:i:s', strtotime("now")), "'n";