繁体   English   中英

strtotime随时区不同

[英]strtotime is different with timezone

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

例如,特定时间是时区“ America / New_York”的“本周一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个小时。 我猜是从America / New_York的-05:00偏移量得出的数字6,加上夏令时1个小时。

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

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

有人可以解释为什么strtotime("now America/New_York")strtotime("now)提前6​​个小时,为什么它们不相等?真的很困惑。

PS:我是格林尼治标准时间+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. 与纽约时间(-0500)的10:39:51对应的返回时间戳

用字符串进行日期操作非常复杂。 试想一下,您将尝试使用字符串函数进行数学运算: 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";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM