Thursday, May 28, 2009

Timezone: PHP, Shell and Crontab

Programming in different timezones can be a headache if not taken care off initially. Codes written to work in one time zone can go wrong when ported to a server that runs on another Timezone. There a few things to take care off when you change from server to server.


By default PHP uses the Timezone that is set in the server or php.ini configuration files. Inorder to make a robust php code that can work in any server environment, it is always a good practice to set the Timezone in the code written.


is the PHP function to set the Timezone in PHP. This can take care of most of the timezone anomalies that can occur in your script when using PHP's Date Function.
Timezone is a string, for example for Indian Standard Time it is "Asia/Calcutta", for LA it is "America/Los_Angeles" etc. Checkout PHP Timezone list for a complete list of timezones.

In a shell the date command gives you the localtime at the SERVER. In order to set the Timezone to your area, we have to set the appropriate environment variable.

export TZ="/usr/share/zoneinfo/{Continent}/{Place}"
export TZ="/usr/share/zoneinfo/Asia/Calcutta"

Add this snippet to your .bashrc to set your timezone to your localtime.

Crontab runs in the same timezone as the server, so for now the best thing to do is calculate the offset between the server timezone and your localtime zone, and plan your crontab accordingly.

For example if you are in IST and the server is in GMT, which has an offset of +05:30 from IST, add your cron such that it runs localtime - 05:30 hrs on the server. ie
localtime - (offset time).

It would be easy to write a script to do this for you.


Anonymous said...

yeah, but what about crontab?