1

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.

4
  • 2
    Probably timezones and/or daylight savings. Check that your PHP and MySQL timezone settings and configs are the same. Commented Jul 11, 2014 at 15:40
  • why don't you use simply SELECT DATE_FORMAT(date, '%d/%m/%Y %H:%i:%s') instead? Commented Jul 11, 2014 at 15:43
  • @VMai: because in the object that's loading the data I want it as a timestamp. That way I can control the presentation format with PHP for different scenarios. Commented Jul 11, 2014 at 15:59
  • I thought so. Maybe you could edit this restriction into your question. Commented Jul 11, 2014 at 16:22

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Cheers, that sounds about right, I'll accept when the time limits done.
0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.