In PHP, working with timezone is quite interesting by utilizing various functions coming under PHP date/time. In this article, we are going to cover the following list of items.
As of PHP version 5.2, it introduces DateTimeZone class in which the function named as listIdentifiers() is defined. This function will return a list of all identifiers as an associative array of string.
This function accepts two optional arguments, like,
We can invoke this function with the references of class name by using PHP scope resolution operator as shown below.
$timezoneIderntifiers = DateTimeZone::listIdentifiers(); print "<pre>"; print_r($timezoneIderntifiers); print "</pre>";
Since DateTimeZone::listIdentifiers() doesn’t have an argument, the above program will return all available time zone to be displayed to the browser.
In PHP, there is an alias of this DateTimeZone class function, which is named as, timezone_identifiers_list(). But, since it is recommended to use the upgraded code as we have seen in the article PHP Array Length, we can prefer DateTimeZone class function shown in the example above.
PHP includes two functions named date_default_timezone_get() and date_default_timezone_set(), as timezone getter and setter respectively.
In the following program, PHP timezone getter returns the value of php.in option until it is overridden by the setter function as shown below.
$timezone_identifier = date_default_timezone_get(); echo $timezone_identifier . "<br/>"; date_default_timezone_set('Asia/Kolkata'); $timezone_identifier = date_default_timezone_get(); echo $timezone_identifier;
In PHP, there is no inbuilt function to convert from one time zone to another. Rather, we can obtain this conversion process by creating a DateTimeZone instance for the required timezone and this instance should be applied it to date time object involved in timezone conversion. For example,
date_default_timezone_set('Asia/Kolkata'); $objDateTime = new DateTime("1978-11-21 12:12:12"); $timezone_array["asian_time"] = $objDateTime->format('d-m-Y H:i:s'); $objDateTimeZone = new DateTimeZone('America/Los_Angeles'); $objDateTime->setTimeZone($objDateTimeZone); $timezone_array["us_time"] = $objDateTime->format('d-m-Y H:i:s'); print "<pre>"; print_r($timezone_array); print "</pre>";
This PHP code tutorial was published on June 27, 2013.