Setting your default timezone with PHP's date_default_timezone_set()
This is an age old problem for many of us, we're hosting our website on a server that is not in the same time zone as we live. For some of us, the difference may be an hour, such as in my case, but I'm aware of people in Australia hosting their sites on a server in the U.S.
This can be a real pain in the neck when writing articles and publishing them on a time-line. I had this problem with my own sNews CMS site here, the server's default time zone was one hour behind my own.
In the old days of PHP3 & PHP4, we would write a time_offset function or something like that to roll back or add the necessary hours to get the time correct for our own use. Well, sNews has no such function and I sure didn't feel like coding it in, so I was pleasantly surprised to discover that was no longer necessary.
Since PHP 5.1.0, you have the function date_default_timezone_set() available. One simply needs to call this with their own timezone at the top of their PHP file and voila, all done.
I put the following at the top of my main PHP file and now all my dates are displayed correctly.
<?php date_default_timezone_set('America/New_York'); ?>
However, this still doesn't fix mysql's default timezone when using the NOW() function, which is used in one of the sNews functions, as well as a couple of my mods, oh well, that's another change for another day.


Comments
RSS Comments Feed
slemborg
I actually tried this method some time ago, but odd this happend, one day my timezones where correct, a few days later they weren't, so what I did, was to use the .htaccess file and added:
php_value date.timezone 'Europe/Copenhagen'
at the very top of the file, which works flawlessly for me.
Matt
.htaccess method is just as good though, helpful too if you need it set site-wide across a lot of files.
slemborg
Patricio
I tried finding some place opposite on the globe to set the timezone...
but I need to set it to yesteday...
is there any easy way to do that?
Matt
Basically, where to you see
date(s('date_format'), strtotime($r['date']));change it to
date(s('date_format'), strtotime("$r[date] -12 hours"));Note the "-12 hours" bit.