English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Basic PHP Tutorial

Advanced PHP Tutorial

PHP & MySQL

PHP Reference Manual

Usage and examples of PHP date_timezone_set() function

PHP Date & Time Function Manual

The date_timezone_set() function sets the timezone of the DateTime object

Definition and usage

date_timezone_set()The function accepts a DateTime object and a timezone object as parameters and sets the specified timezone for the given date and time.

Syntax

date_timezone_set($object, $timezone)

Parameter

Serial numberParameters and descriptions
1

object (required)

This indicates the DateTime object for which the timezone needs to be set.

2

timezone (required)

This is a TimeZone object representing the timezone you need to set for the DateTime object.

Return value

The date_timezone_set function returns a DateTime object. If it fails, it returns a boolean valuefalse.

PHP version

This function was originally introduced in PHP version5.2introduced in version 7.2.0 and can be used in all higher versions.

Online example

The following examples usedate_timezone_set()and timezone_name_get() function-

<?php
   $date = date_create("25-09-1989"); 
   $tz = new DateTimeZone('Asia/Shanghai');   
   $res = date_timezone_set($date, $tz);   
   print("Timezone: ".timezone_name_get(date_timezone_get($date)));
?>
Test and see‹/›

Output result

Timezone: Asia/Shanghai

Online example

The following example creates a DateTime object and a timezone, and sets the timezone to another value-

<?php
   $date = new DateTime("25-09-1989", new DateTimeZone('Asia/Shanghai')); 
   $res = date_timezone_set($date, timezone_open("Indian/Kerguelen"));   
   print("Timezone: ".timezone_name_get(date_timezone_get($date)));
?>
Test and see‹/›

Output result

Timezone: Indian/Kerguelen

Online example

<?php
   $dateSrc = '2007-04-19 12:50 GMT';
   $dateTime = date_create($dateSrc);
   $DateTimeZone = timezone_open('Asia/Shanghai');
   date_timezone_set($dateTime, $DateTimeZone);
   $NewDateTimeZone = date_timezone_get($dateTime);   
   echo 'The new timezone is '. timezone_name_get($NewDateTimeZone);
   echo "\n";
   # Use the second function.
   $dateTime = new DateTime($dateSrc);
   $DateTimeZone = timezone_open('Asia/Shanghai');
   $dateTime-setTimezone($DateTimeZone);
   $NewDateTimeZone = $dateTime;-getTimezone();   
   echo 'The new timezone is '. timezone_name_get($NewDateTimeZone);
?>
Test and see‹/›

Output result:

The new timezone is America/Chicago
The new timezone is America/Chicago