This can be confusing, especially when using the
date() function on a PHP page –
date("Y") will obviously provide the right year 99.99% of the time, but
date('l’) (a lowercase L, to generate the name of the day) will sometimes be right for your location (when Germany happens to be in the same day) and sometimes not (when Germany is one day ahead of you)*.
While you can look through the php.ini file or phpinfo() to locate the default timezone information, most people will probably find it easier to display it on a PHP page with a temporary line of code:
<?php echo date_default_timezone_get(); ?>
This will provide you with the geographical area that PHP assumes it is located in. Note that this information is provided in the format city/region. If "America" is referred to, it includes the entire continent, from the frozen north of Nunavut to Tierra del Fuego. Also note that the city location references the primary or capital city of the area, and does not recognize inter-city or national rivalries, so (for example) the correct timezone for Alberta is Edmonton, America.
If the timezone displayed on this test page is not correct, you can try editing the server’s php.ini file, but this may not be possible in a hosted web environment. Most people will find it easier to correct the timezone on the PHP page itself, before you calculate a date or time.
For any PHP5 script that needs to reference the exact local time on a server with an incorrect timezone, before you use any date or time functions, write:
<?php date_default_timezone_set('America/Edmonton'); ?>
(php.net has a complete list of PHP timezone values: find the one nearest and most relevant to you, replacing
'America/Edmonton' with the appropriate location).
If you follow this line with
echo date_default_timezone_get() you’ll find that the timezone is now correct, as are all calculated dates. You just have to remember to start any page that uses PHP-generated time or date values with this line. It’s not unusual to ensure this by making it part of an
include for every page:
<? date_default_timezone_set('America/Edmonton'); ?> <!DOCTYPE html> <head>
With this in place, confusing time results in PHP should be a thing of the past.
* this, of course, assumes you are not in Germany
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.