Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - date_default_timezone_set not working, Why?

Tags:

timezone

php

date_default_timezone_set not working.

my code:

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>";

all of them return the same date "2017-05-26 12:47:08 CST", why?


update:

I have fixed this problem, the reason is that I used the wrong way to change the timezone on CentOS7:

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

this way is right on CentOS6, but in CentOS7 /etc/localtime is linked to /usr/share/zoneinfo/Etc/UTC, so I damaged the UTC timezone.

the right way to change the timezone on CentOS7 is:

timedatectl set-timezone "Asia/Shanghai"

or

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

so I copied /usr/share/zoneinfo/Etc/UTC from other system to my system to fixed this problem.

like image 689
gdtv Avatar asked May 26 '26 08:05

gdtv


1 Answers

Try This.

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

time() is timezone independant. This means, it will always return the time in seconds since january 1 1970, no matter how the timezone is configured. It always takes the UTC-time.'

date_default_timezone_set(); NOT working

Also Check this http://php.net/manual/pl/function.time.php#100220

like image 69
Adharsh M Avatar answered Jun 03 '26 13:06

Adharsh M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!