PHP DateTimeZone __construct() Method
The PHP DateTimeZone::__construct() method returns a new DateTimeZone object. The timezone_open() function is an alias of this method.
Syntax
//Object-oriented style public DateTimeZone::__construct(timezone) //Procedural style timezone_open(timezone)
Parameters
timezone |
Required. Specify a string value representing one of the supported timezones. |
Return Value
Returns a new DateTimeZone object on success. Procedural style returns false on failure.
Exceptions
Throws Exception if the timezone supplied is not recognized as a valid timezone.
Example: using both styles
The example below shows the usage of DateTimeZone::__construct() method.
<?php //creating a DateTimeZone object //using object-oriented style $tz1 = new DateTimeZone("Europe/London"); //displaying the DateTimeZone print_r($tz1); echo "\n"; //creating a DateTimeZone object //using procedural style $tz2 = timezone_open("America/Chicago"); //displaying the DateTimeZone print_r($tz2); ?>
The output of the above code will be:
DateTimeZone Object ( [timezone_type] => 3 [timezone] => Europe/London ) DateTimeZone Object ( [timezone_type] => 3 [timezone] => America/Chicago )
Example: using DateTimeZone object
The DateTimeZone object can be used to create a DateTime object with given timezone or modify the timezone of a given DateTime object. Consider the example below:
<?php //creating a DateTimeZone object $tz1 = new DateTimeZone("Europe/London"); //creating a DateTime object $date = new DateTime("10-May-2015", $tz1); //getting the current time zone $curr_tz = $date->getTimezone(); echo "Current TimeZone: ".$curr_tz->getName()."\n"; //creating another DateTimeZone object $tz2 = new DateTimeZone("America/Chicago"); //setting the timezone of a date to new value $date->setTimezone($tz2); //getting the modified time zone $mod_tz = $date->getTimezone(); echo "Modified TimeZone: ".$mod_tz->getName()."\n"; ?>
The output of the above code will be:
Current TimeZone: Europe/London Modified TimeZone: America/Chicago
❮ PHP Date and Time Reference