PHP Function Reference

PHP DateTime - getTimezone() Method



The PHP DateTime::getTimezone() method returns the time zone relative to given DateTime. The date_timezone_get() function is an alias of this method.

Note: This method is defined under DateTimeInterface interface. DateTime and DateTimeImmutable classes inherit this method from DateTimeInterface interface.

Syntax

//Object-oriented style
public DateTime::getTimezone()
public DateTimeImmutable::getTimezone()
public DateTimeInterface::getTimezone()

//Procedural style
date_timezone_get(object)

Parameters

object Required. For procedural style only: A DateTime object returned by date_create().

Return Value

Returns a DateTimeZone object on success or false on failure.

Example: using both styles

The example below shows the usage of DateTime::getTimezone() method.

<?php
  //creating a DateTime object
  $date = new DateTime(null, new DateTimeZone('Europe/London'));

  //getting the timezone using Object-oriented style
  $tz = $date->getTimezone();
  echo "TimeZone: ".$tz->getName()."\n";

  //getting the timezone using Procedural style
  $tz = date_timezone_get($date);
  echo "TimeZone: ".timezone_name_get($tz)."\n";
?>

The output of the above code will be:

TimeZone: Europe/London
TimeZone: Europe/London

Example: Timezone of a DateTime object

Consider the example below where the timezone of a DateTime object is returned using this method.

<?php
  //creating a DateTime object
  $date = new DateTime(null, new DateTimeZone('Europe/London'));

  //getting the timezone
  $tz = $date->getTimezone();
  echo "Initial TimeZone: ".$tz->getName()."\n";

   //setting the timezone to a new value
   $date->setTimezone(new DateTimeZone('America/Chicago'));

  //getting the timezone
  $tz = $date->getTimezone();
  echo "Final TimeZone: ".$tz->getName()."\n";
?>

The output of the above code will be:

Initial TimeZone: Europe/London
Final TimeZone: America/Chicago

Example: timezone of a DateTimeImmutable object

Similarly, this method can be used with DateTimeImmutable object also. Consider the example below:

<?php
  //creating a DateTimeImmutable object
  $date = new DateTimeImmutable(null, new DateTimeZone('Europe/London'));

  //getting the timezone
  $tz = $date->getTimezone();
  echo "TimeZone: ".$tz->getName()."\n";
?>

The output of the above code will be:

TimeZone: Europe/London

❮ PHP Date and Time Reference