【问题标题】:Why does strtotime return the same result for different timezones为什么strtotime对不同的时区返回相同的结果
【发布时间】:2013-01-28 10:21:46
【问题描述】:

我正在使用 php 和 mysql 来开发我的应用程序。对于此应用程序,时间起着重要作用,因为我想根据用户选择的时区向他们显示数据。为此,我使用 strtotime 将时间转换为数字形式,但我只是注意到 strtotime 为所有时区返回相同的值。我编写了以下代码进行测试。

date_default_timezone_set("Asia/Kolkata");
echo date("Y-m-d H:i:s")." ------ ";
echo strtotime(date("Y-m-d H:i:s"))."<br/><br/>";
date_default_timezone_set("America/New_York");
echo date("Y-m-d H:i:s")." ------ ";
echo strtotime(date("Y-m-d H:i:s"));

但是输出是

2013-01-28 15:40:11 ------ 1359367811

2013-01-28 05:10:11 ------ 1359367811

为什么返回值相同?

【问题讨论】:

标签: php strtotime unix-timestamp date-conversion


【解决方案1】:

【讨论】:

    【解决方案2】:

    正如@Bobby 的评论所述,“Unix 时间戳始终为 UTC”。这意味着您实际上是在对 UTC 时区进行两次等效转换。

    考虑 t1 时间戳在 1 时区 和相同 t2 中的 >1 时间戳在转换为 timezone a3 时会产生相同的结果。在您的示例中,“相同的结果”以秒为单位,但原理是相同的。

    换句话说,在您的代码中,您从看似两个不同的日期生成两个 UNIX 时间戳。但是您实际上所做的是生成同一时间点的两个不同但等效的表示(亚洲和美国时区)。然后,您将两个等效表示转换为相同的第三个表示(UTC 时区)。

    【讨论】:

      【解决方案3】:

      根据strtotime 的 PHP 手册,

      The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.

      如上所述,strtotime 将给定的日期格式转换为 Unix 时间戳,该时间戳是相对于 Unix 纪元计算的。纪元是一个固定点,其定义与用户所在的时区无关,从那时起的秒数在所有时区中相对相同。

      设置时区只会影响时间戳值的解释。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-01
        • 1970-01-01
        • 2020-10-12
        • 2017-10-17
        • 2012-07-28
        • 2013-03-10
        • 1970-01-01
        • 2016-08-30
        相关资源
        最近更新 更多