The setTimezone Method of the DateTime Class
The setTimezone
method changes the time zone of a DateTime
object. It accepts an object of the DateTimeZone
class as a parameter. Returns the modified DateTime
object.
Syntax
public DateTime::setTimezone(DateTimeZone $timezone): DateTime
Example
Let's set the 'America/New_York' time zone for the current date:
<?php
$date = new DateTime('now', new DateTimeZone('UTC'));
$date->setTimezone(new DateTimeZone('America/New_York'));
echo $date->format('Y-m-d H:i:s');
?>
Code execution result:
'2023-11-15 10:30:00'
Example
Let's change the time zone of an existing DateTime
object:
<?php
$date = new DateTime('2023-01-01 12:00:00', new DateTimeZone('Europe/Moscow'));
$date->setTimezone(new DateTimeZone('Asia/Tokyo'));
echo $date->format('Y-m-d H:i:s');
?>
Code execution result:
'2023-01-01 18:00:00'
See Also
-
the
date
function,
which formats a date/time -
the
date_default_timezone_set
function,
which sets the default time zone -
the
DateTimeZone
class,
which represents a time zone