PHP and timezone conversions
This morning I was working on setting up the different timezones in Juvely and was amazed that PHP does not (currently) have any easy to use functions for converting between different timezones. We have all the times and dates stored as GMT in the database, and use the following to get a certain time into a format MySql understands:
$time = gmdate(’Y-m-d H:i:s’);
To then get it back into a timestamp when retrieving stuff from the database I originally used the following:
$time = strtotime($db_time);
To change the timezones I decided to just use date_default_timezone_set($timezone), which changes the timezone in which all date functions work. I got confused for a while as to why when I had it set to Paris and London it displayed the same time. Then I realised that strtotime() is a date function as well so that thinks the time being parsed to it is the local time.
Luckily it turns out that there is an easy solution to this to make strtotime() behave as I intended, just append GMT to the end of the time and it will know it is in GMT! I am not sure how this would work for other timezones but I would imagine you would just do something like GMT-0800 if the timezone is 8 hours behind.
The full code of how this would work goes like this:
date_default_timezone_set(’Europe/Paris’);
$time = strtotime($db_time . ‘ GMT’);
echo ‘It is ‘ . date(’jS of F, Y g:i a’);