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 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 argument, the above program will return all available timezone 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 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 in-built function to convert from one timezone to another. Rather, we can obtain this conversion process by creating DateTimeZone instance for the required timezone and this instance should be applied it to datetime object involved in timezone convertion. 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 tutorial was added on June 27, 2013.