Converting a UTC date time to local in PHP

Here is a thing that took me longer to work out than it should have. I am storing some dates in a MySql database in the UTC timezone, but on my webpage I want to have them show as the local time. The problem I found is that PHP assumed that the date from the database was already in the local time (BST) and so did not adjust the hour on the datetime object when the timezone was applied.

This is fixed by setting the timezone when creating the datetime object from the string:

Also here it is again, but with a Unix Timestamp:

I hope this saves someone half a day. Although it occurs to me that I should really have the PHP output the date as the UTC and then have the javascript deal with it. Then the date would be displayed as how the users timezone is set rather than the servers.

So, in our PHP code, we setup a suitable output:

and in your javascript file, after you have picked up the data with your ajax call, or whatever, I have two functions, one to convert the ISO 8601 format (YYYY-MM-DDTHH:mm:ss.sssZ) UTC date time to local and another to make for a nicely formatted output:

I’ve created the separate function for the date formatting as this has more flexibility.

Links and Sources

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.