简体   繁体   中英

Mysql, PHP and UTC_TIMESTAMP()

I know there's a hundred questions on here about this topic, but I've read them all and still am not getting it.

I'm storing the date I last hit an API in a settings table using UTC_TIMESTAMP() . The column type is a mysql timestamp :

UPDATE settings SET last_pull = UTC_TIMESTAMP();

When I select this from mysql I get the following:

mysql> select last_pull from settings;
+---------------------+
| last_pull           |
+---------------------+
| 2015-06-30 23:05:00 |
+---------------------+
1 row in set (0.00 sec)

Seems clear, since I'm on Pacific time, that UTC time is 8 hours ahead. Therefore it was 16:05:00 local time when I created that record. (It was actually 16:05 local time-- I was there!)

What's confusing me is that when I pull the data back out of the DB, according to every answer on here, I should be able to use the default PHP date or datetime functions, and assuming I have my timezone properly set, I should get the local time from that timestamp (eg. date('Ymd H:i:s', $last_pull_value) should return 2015-06-30 16:05:00 ).

Is this assumption incorrect? I've verified my timezones for linux and PHP are correct, and that mysql is properly set as well.

Yet when I do

$last_pull = new DateTime();
$last_pull->setTimestamp($row['last_pull']);                

var_dump($last_pull->format("c"));

it returns:

"2015-06-30 23:05:00"

So then I explicitly set the timezone:

$last_pull = new DateTime();
$last_pull->setTimestamp($row['last_pull']);    
$last_pull->setTimezone(new DateTimeZone('America/Los_Angeles'));           

var_dump($last_pull->format("c"));

And it returns the exact same thing (makes sense if the default TZ was correct to begin with).

"2015-06-30 23:05:00"

My question is how do I get the local time when the API last pulled? Why won't the datetime function return 16:05:00?

Thanks

If you set the timezone for your DateTime object on initialisation, It will work as you expect.

$last_pull = new DateTime('2015-06-30 23:05:00', new DateTimeZone('UTC'));
var_dump($last_pull->format("c")); //string(25) "2015-06-30T23:05:00+00:00"
$last_pull->setTimezone(new DateTimeZone('America/Los_Angeles'));
var_dump($last_pull->format("c")); //string(25) "2015-06-30T16:05:00-07:00"

The DateTime object's documentation notes that the default timezone used for a new date time object is your current timezone - http://php.net/manual/en/datetime.construct.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM