• PHP Video Tutorials

PHP date_timezone_set() Function


Advertisements

Definition and Usage

The date_timezone_set() function accepts a DateTime object and a timezone object as parameters and, sets the specified timezone to the given DateTime.

Syntax

date_timezone_set($object, $timezone)

Parameters

Sr.No Parameter & Description
1

object (Mandatory)

This represents the DateTime object for which you need to set the timezone.

2

timezone (Mandatory)

This is a TimeZone object representing the time zone you need to set to the DateTime object.

Return Values

The date_timezone_set function returns a DateTime object. Incase of failure it returns the boolean value false.

PHP Version

This function was first introduced in PHP Version 5.2.0 and, works with all the later versions.

Example

Following example of the date_timezone_g=set() function −

Live Demo
<?php
   $date = date_create("25-09-1989"); 
   $tz = new DateTimeZone('Indian/Mahe');   
   $res = date_timezone_set($date, $tz);   
   print("Timezone: ".timezone_name_get(date_timezone_get($date)) );
?>

This will produce following result −

Timezone: Indian/Mahe

Example

Following example create a DateTime object along with the timezone and, set the timezone to another value −

Live Demo
<?php
   $date = new DateTime("25-09-1989", new DateTimeZone('Indian/Mahe')); 
   $res = date_timezone_set($date, timezone_open("Indian/Kerguelen"));   
   print("Timezone: ".timezone_name_get(date_timezone_get($date)) );
?>

This will produce following result −

Timezone: Indian/Kerguelen

Example

<?php
   $dateSrc = '2007-04-19 12:50 GMT';
   $dateTime = date_create( $dateSrc);
   $DateTimeZone = timezone_open ( 'America/Chicago' );
   date_timezone_set( $dateTime, $DateTimeZone );
   $NewDateTimeZone = date_timezone_get($dateTime);   
   echo 'New timeZone is '. timezone_name_get($NewDateTimeZone);
   echo "\n";
   # Using second function.
   $dateTime = new DateTime($dateSrc);
   $DateTimeZone = timezone_open ( 'America/Chicago' );
   $dateTime->setTimezone( $DateTimeZone );
   $NewDateTimeZone = $dateTime->getTimezone ();   
   echo 'New timeZone is '. timezone_name_get ($NewDateTimeZone);
?>

This will produce the following result −

New timeZone is America/Chicago
New timeZone is America/Chicago
php_function_reference.htm
Advertisements