2017-05-26 41 views
1

date_default_timezone_set不起作用。php - 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年5月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到解決了這個問題。

回答

2

試試這個。

<?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

+0

請參見上面的代碼,我也嘗試 「回聲日期( 'YMD H:我:■T')」,這不包括時間(),但它返回相同的結果。我也嘗試:$ 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(中國)? – gdtv

+0

@gdtv但是在你回覆那個日期之前,你將時區設置爲UTC。所以echo date(time())將與你的echo相同,因爲它們都是UTC – Andreas