diggersworld
diggersworld

Reputation: 13080

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.

Upvotes: 1

Views: 74

Answers (2)

1stmajor
1stmajor

Reputation: 11

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!

Upvotes: 0

deceze
deceze

Reputation: 522081

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.

Upvotes: 4

Related Questions