Working with Timezones in PHP

PHP

It is very important to pay attention to time zones in PHP. Your server might be hosted in one location while your visitors might be in another time zone. The local time of your visitors will be different from your server’s. To handle such differences, there are several inbuilt PHP functions. These functions allow you to easily tell the timezone of your server, change it and convert them to local date/time.

The first thing that you need to do is figure out the default timezone of your PHP server.

Here’s how:

<?php
echo date_default_timezone_get();
?>
Output:
America/Chicago

If you need to change it to your desired timezone, here’s how:

<?php
date_default_timezone_set("Asia/Kathmandu");
echo date_default_timezone_get();
?>
Output:
Asia/Kathmandu

To find the entire list of Timezones in PHP visit this page.

Here’s an example where we use an array containing different Timezones. Those Timezones are set as default with the help of a foreach loop. Then the current time is printed.

Example:

<?php
$timezones = array('Europe/London', 'America/Chicago', 'Asia/Kathmandu');
foreach($timezones as $value){
date_default_timezone_set($value);
echo date_default_timezone_get();
echo' - ';
echo date("h:m:s");
echo "<br />";
}
?>
Output
Europe/London - 07:10:20
America/Chicago - 02:10:20
Asia/Kathmandu - 01:10:20

Sometimes it is necessary to calculate the timezone offset. Here is how you do it:

<?php
$timezone=timezone_open("Asia/Kathmandu");
$date=date_create("now",$timezone);
echo timezone_offset_get($timezone,$date);
echo "<br />";
?>
Output:
20700

The above example computed the offset of Kathmandu as 20700 seconds from GMT i.e. GMT + 5.75. There’s a whole lot of timezone constructs that are used in Object Oriented PHP programming.