Posts Tagged ‘.htaccess’

Keeping PHP and mySQL dates in sync

Wednesday, May 16th, 2012

My websites are hosted with Hostgator in Texas, USA but most of my customers are based in the UK. This creates a potential problem with dates and times because we usually want timestamps etc. to be recorded as if they were in the UK timezone rather than the timezone where the server is.

Setting the timezone for Apache

Fortunately it is easy to tell Apache to use a different timezone, just add the following line to your .htaccess file.

SetEnv TZ Europe/London

This works nicely to set the timezone for the webserver and the programs that run within it, including PHP. This means that the PHP date and time functions will return the date/time as UK time rather than the server time.

Getting mySQL to use the right time

The only problem is that Apache doesn’t control mySQL, in fact on a shared hosting arrangement it isn’t possible to set mySQL’s timezone. I would be changing it for all the customers on my server which would suit me fine but may not make them happy.

This means that using a mySQL function like NOW() generates a Texas timestamp rather than a London timestamp which isn’t what I want. There are a number of solutions to this problem, Richard Lord has written a good, clear post about possible solutions on his blog.

What I want is something that uses the timezone from Apache but stores the date in a mySQL format so I can use mySQL date comparisons when I retrieve the data later on. Fortunately the answer is quite straightforward; Where I would use NOW() to generate a timestamp I use the PHP function:

date('Y-m-d H:i:s')

This uses the current date from Apache (which is set to the London timezone) but converts it to the mySQL DATETIME format so that you can use mySQL’s date processing functions on the data. Of course if you had calculated some other date in your PHP code you could use the same function but pass your calculated date to the function instead of letting it use the current date/time

date('Y-m-d H:i:s',$my_date)

So the SQL query you construct in PHP might look a bit like this:


$query = 'INSERT INTO filename (
          current_time_stamp,
          my_time_stamp)
          VALUES ("' . 
          date('Y-m-d H:i:s') . '", '" .          // replaces NOW()
          date('Y-m-d H:i:s',$my_date) . '")';    // replaces calculated date

That solved my particular date/time problem, I hope it helps you too.