简体   繁体   中英

MySQL UNIX_TIMESTAMP acting weird

In my database I have a datetime field with the following value 2014-07-21 00:00:00 .

When I pull the data I have the line:

SELECT UNIX_TIMESTAMP(date) AS `date` ...

When I then use PHP date to format it for human reading the following happens:

echo date('d/m/Y H:i:s', $row['date']);
// outputs 20/07/2014 23:00:00

I don't understand what's doing this.

It's a timezone problem. 2014-07-21 00:00:00 will convert to very different UNIX timestamps depending on what timezone the database assumes this time to be in. Conversely, PHP will convert the UNIX timestamp to the human-readable version depending on the timezone set with date_timezone_default_set . You'll have to ensure that MySQL's internal timezone setting and PHP's internal timezone setting are identical if you expect the same value to be output.

I replicated the same in my database and I got exactly the same value. I cannot say if you and I are in the same timezone, but one thing is sure - according to the documentation Here

If UNIX_TIMESTAMP() is called with a date argument, it returns the value of the argument as seconds since '1970-01-01 00:00:00' UTC

That explains the disparity. To solve the problem you can select the date normally and use strtotime in php to convert it to timestamp. As in

SELECT date AS `date` ...
echo date('d/m/Y H:i:s', strtotime($row['date']));

Hope this helps..cheers!

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