PHP DateTime - setTimezone() Method
The PHP DateTime::setTimezone() method sets the timezone of a DateTime object. The date_timezone_set() function is an alias of this method.
Syntax
//Object-oriented style public DateTime::setTimezone(timezone) //Procedural style date_timezone_set(object, timezone)
Parameters
object |
Required. For procedural style only: A DateTime object returned by date_create(). |
timezone |
Required. Specify a DateTimeZone object representing the desired time zone. |
Return Value
Returns the DateTime object with modified timezone on success, otherwise returns false.
Example: using both styles
The example below shows the usage of DateTime::setTimezone() method.
<?php //creating a DateTime object $date = new DateTime(); //setting timezone using Object-oriented style $date->setTimezone(new DateTimeZone('America/Chicago')); //formatting the datetime to print it echo $date->format("d-M-Y H:i:s P")."\n"; //setting timezone using Procedural style date_timezone_set($date, new DateTimeZone('Europe/London')); //formatting the datetime to print it echo $date->format("d-M-Y H:i:s P")."\n"; ?>
The output of the above code will be:
11-Sep-2021 05:13:38 -05:00 11-Sep-2021 11:13:38 +01:00
Example: Modifying timezone of a DateTime object
This method can be used to modify timezone of the DateTime object to a new value. Consider the example below:
<?php //datetime string $datetime_string = "14-May-2015 5:10 GMT+2"; //creating a DateTime object $date = new DateTime($datetime_string); //formatting the datetime to print it echo "Original DateTime: ".$date->format("d-M-Y H:i:s P")."\n"; //setting timezone to a new value $date->setTimezone(new DateTimeZone('America/Chicago')); //formatting the datetime to print it echo "Modified DateTime: ".$date->format("d-M-Y H:i:s P")."\n"; ?>
The output of the above code will be:
Original DateTime: 14-May-2015 05:10:00 +02:00 Modified DateTime: 13-May-2015 22:10:00 -05:00
❮ PHP Date and Time Reference