【问题标题】:php - date_default_timezone_set not working, Why?php - date_default_timezone_set 不起作用,为什么?
【发布时间】:2017-05-26 04:50:24
【问题描述】:

date_default_timezone_set 不起作用。

我的代码:

ini_set('display_errors', true);
error_reporting(E_ALL);

date_default_timezone_set("UTC");
echo date('Y-m-d H:i:s T') . "<br>";
echo date('Y-m-d H:i:s T', time()) . "<br>";
date_default_timezone_set("Asia/Shanghai");
echo date('Y-m-d H:i:s T') . "<br>";
echo date('Y-m-d H:i:s T', time()) . "<br>";
ini_set("date.timezone","UTC");
echo date('Y-m-d H:i:s T') . "<br>";
echo date('Y-m-d H:i:s T', time()) . "<br>";
ini_set("date.timezone","Asia/Shanghai");
echo date('Y-m-d H:i:s T') . "<br>";
echo date('Y-m-d H:i:s T', time()) . "<br>";

他们都返回相同的日期“2017-05-26 12:47:08 CST”,为什么?


更新:

我已经修复了这个问题,原因是我在CentOS7上使用了错误的方式更改时区:

cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

这种方式在 CentOS6 上是正确的,但在 CentOS7 中 /etc/localtime 链接到 /usr/share/zoneinfo/Etc/UTC,所以我损坏了 UTC 时区。

在 CentOS7 上更改时区的正确方法是:

timedatectl set-timezone "Asia/Shanghai"

ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

所以我将 /usr/share/zoneinfo/Etc/UTC 从其他系统复制到我的系统以解决此问题。

【问题讨论】:

    标签: php timezone


    【解决方案1】:

    试试这个。

    <?php
        $now = new DateTime();
        $now->setTimezone(new DateTimeZone('America/Los_Angeles'));
        echo $now->format('Y-m-d H:i:s T');
    ?>
    

    time() 与时区无关。这意味着,无论时区如何配置,它将始终以秒为单位返回自 1970 年 1 月 1 日以来的时间。它总是需要 UTC 时间。'

    date_default_timezone_set(); NOT working

    也检查一下 http://php.net/manual/pl/function.time.php#100220

    【讨论】:

    • 请看上面的代码,我也试试“echo date('Y-m-d H:i:s T')”,这不包括time(),但它返回相同的结果。我也尝试:$now = new DateTime(); $now->setTimezone(new DateTimeZone('UTC')); echo $now->format('Y-m-d H:i:s T')。 "
      ";它返回:2017-05-26 13:14:27 CST,为什么时区是 CST(chine)?
    • @gdtv 但就在您回显该日期之前,您将时区设置为 UTC。所以 echo date( time()) 将与您的 echo 相同,因为它们都是 UTC
    猜你喜欢
    • 2012-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-02
    • 2016-12-31
    • 2013-08-08
    • 1970-01-01
    相关资源
    最近更新 更多