Setting your default timezone with PHP's date_default_timezone_set()

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.



You might like



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.

Hmmm, I wonder why it was being over-written?

.htaccess method is just as good though, helpful too if you need it set site-wide across a lot of files.

I've no idea why it happen, but the .htaccess did sort it, and for me that's fine, although, i'd like to find out why it all of a sudden just "rolled back" to default.

I need to set the date to -12 hours before NOW...
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?

Patricio, I don't think you can do that with timezones, you'd need to manipulate the actual date returned before formatting it. If you're using sNews, you'd do something like this;

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.

Comments are closed. No new comments allowed.

Copyleft 2002 - 2017 Matt Jones
Hand crafted with HTML5 & CSS3
↑ Back to top