• PHP Video Tutorials

PHP date_default_timezone_set() Function



Definition and Usage

The date_default_timezone_set() function is used to set the default timezone used by all the functions in a script.

Syntax

date_default_timezone_set(timezone)

Parameters

Sr.No Parameter & Description
1

timezone (Mandatory)

This is the string representing the time zone you need to set as default.

Return Values

PHP date_default_timezone_set() function returns a boolean value which is true if the given timezone string is valid and, false if it is not valid.

PHP Version

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

Example

Following example demonstrates the usage of the date_default_timezone_set function −

Live Demo
<?php
   //setting the timezone
   $tz = 'Indian/Mahe';   
   date_default_timezone_set($tz);
   $timeZone = date_default_timezone_get();
   print("Default timezone: ".$timeZone);
?>

This will produce following result −

Default timezone: Indian/Mahe

Example

Following example compares the default time zone and the ini-set timezone. −

<?php
   //setting the timezone
   $tz = 'Asia/Kolkata';   
   date_default_timezone_set($tz);
   //Retrieving the default timezone
   $timeZone = date_default_timezone_get();
   print("Default timezone: ".$timeZone);
   print("\n");

   //Comparing the timezone with ini-set timezone 
   if (strcmp($timezone, ini_get('date.timezone'))){ 
      print('Script timezone and ini-set timezone are not same.'); 
   } else { 
      print('Script timezone and ini-set timezone are same.'); 
   } 
?>

This will produce following result −

Array
Default timezone: Asia/Kolkata
Script timezone and ini-set timezone are same.

Example

$dateSrc = '2007-04-19 12:50 GMT';
$dateTime = date_create( $dateSrc);;
$DateTimeZone = date_timezone_get ( $dateTime );
   
echo 'Return timeZone is '. timezone_name_get ($DateTimeZone);
echo "\n";

# Using second function.
$dateTime = new DateTime($dateSrc);
$DateTimeZone = $dateTime->getTimezone ();
   
echo 'Return timeZone is '. timezone_name_get ($DateTimeZone);

This will produce the following result −

Return timeZone is America/Denver
Return timeZone is America/Denver
php_function_reference.htm
Advertisements