【问题标题】:php strtotime strange behaviorphp strtotime 奇怪的行为
【发布时间】:2014-07-08 12:29:34
【问题描述】:

我目前正在为 php 应用程序使用时区。

我发现 strtotime 似乎没有连贯的行为。 这个例子突出了我在说什么:

var_dump("strtotime('now'), UTC, Europe/Paris and America/New_York");
date_default_timezone_set('UTC');
var_dump(strtotime('now'));
date_default_timezone_set('Europe/Paris');
var_dump(strtotime('now'));
date_default_timezone_set('America/New_York');
var_dump(strtotime('now'));

var_dump("strtotime('now UTC'), UTC, Europe/Paris and America/New_York");
date_default_timezone_set('UTC');
var_dump(strtotime('now UTC'));
date_default_timezone_set('Europe/Paris');
var_dump(strtotime('now UTC'));
date_default_timezone_set('America/New_York');
var_dump(strtotime('now UTC'));

var_dump("strtotime('today'), UTC, Europe/Paris and America/New_York");
date_default_timezone_set('UTC');
var_dump(strtotime('today'));
date_default_timezone_set('Europe/Paris');
var_dump(strtotime('today'));
date_default_timezone_set('America/New_York');
var_dump(strtotime('today'));

var_dump("strtotime('today UTC'), UTC, Europe/Paris and America/New_York");
date_default_timezone_set('UTC');
var_dump(strtotime('today UTC'));
date_default_timezone_set('Europe/Paris');
var_dump(strtotime('today UTC'));
date_default_timezone_set('America/New_York');
var_dump(strtotime('today UTC'));

结果:

string 'strtotime('now'), UTC, Europe/Paris and America/New_York'
int 1404821878
int 1404821878
int 1404821878
string 'strtotime('now UTC'), UTC, Europe/Paris and America/New_York'
int 1404821878
int 1404829078
int 1404807478
string 'strtotime('today'), UTC, Europe/Paris and America/New_York'
int 1404777600
int 1404770400
int 1404792000
string 'strtotime('today UTC'), UTC, Europe/Paris and America/New_York'
int 1404777600
int 1404777600
int 1404777600

strtotime('foo UTC') 应始终返回 UTC 时间戳,无论 date_default_timezone_get() 返回什么。

它适用于strotime('today UTC'),在此示例中总是返回1404777600。 此外,strtotime('today') 根据设置的时区,按预期返回不同的时间戳。

但在调用strtotime('now UTC')时却有相反的行为,返回时区设置的不同时间戳函数,调用strtotime('now')时总是返回1404821878

这是一个错误还是我误解了什么?

提前致谢

【问题讨论】:

    标签: php timezone strtotime


    【解决方案1】:

    strtotime('now UTC') 采用您所在时区的当前时间,将其解释为本地时间 UTC 并返回结果。即:

    strtotime('now UTC') → strtotime('2014-07-08 14:35:00 UTC') → result
    

    如果您省略“UTC”,则不会发生这种转换,因为“现在”就是“现在”,在世界任何地方。

    顺便说一句:无论如何,我永远不会依赖strtotime 更深奥的自动时间数学,因为它通常甚至没有很好的定义。 strtotime 返回一个精确到秒的时间戳。在这种情况下,“今天”究竟意味着什么? “现在 UTC”到底是什么意思? “+1 个月”到底是什么意思? strtotime 非常适合将 complete 时间戳字符串(如 2014-07-08 14:35:00 Europe/Berlin)转换为 UNIX 时间戳。任何比这更模棱两可的东西通常都会产生未定义的结果。

    【讨论】:

      猜你喜欢
      • 2017-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-08
      相关资源
      最近更新 更多