PHP Function Reference

PHP DateTimeImmutable - setTimezone() Method



The PHP DateTimeImmutable::setTimezone() method returns a DateTimeImmutable object with timezone set to the specified timezone.

Syntax

public DateTimeImmutable::setTimezone(timezone)

Parameters

timezone Required. Specify a DateTimeZone object representing the desired time zone.

Return Value

Returns a new DateTimeImmutable object with timezone set to the specified timezone on success, otherwise returns false.

Example: Sets the timezone

The example below shows the usage of DateTimeImmutable::setTimezone() method.

<?php
  //datetime string
  $datetime_string = "14-May-2015 5:10 GMT+2";

  //creating a DateTimeImmutable object
  $date = new DateTimeImmutable($datetime_string);

  //creating a new DateTimeImmutable object 
  //with timezone set to new value
  $date_new = $date->setTimezone(new DateTimeZone('America/Chicago')); 

  //formatting the datetime to print it
  echo "Original DateTime: ".$date->format("d-M-Y H:i:s P")."\n";
  echo "New DateTime:      ".$date_new->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
New DateTime:      13-May-2015 22:10:00 -05:00

❮ PHP Date and Time Reference