date_diff> <date_default_timezone_get
Last updated: Fri, 16 Jul 2010

date_default_timezone_set

(PHP 5 >= 5.1.0)

date_default_timezone_set Configura a timezone padrão a ser utilizada por todas as funções de data e hora em um script

Descrição

bool date_default_timezone_set ( string $timezone_identifier )

date_default_timezone_set() configura a timezone padrão a ser utilizada por todas as funções de data e hora em um script

Nota: Desde o PHP5.1.0 (quando as funções de data e tempo foram reescritas), toda chamada a esse tipo de função irá gerar um E_NOTICE se a timezone não é válida, e/ou uma mensagem E_STRICT se estiver utilizando as configurações do sistema ou a variável de ambiente TZ.

Ao invés de utilizar essa função para setar a timezone padrão no seu script, você pode também utilizar a configuração INI date.timezone para configurar a timezone padrão.

Parâmetros

timezone_identifier

O identificador da timezone, como UTC ou Europe/Lisbon. A lista de identificadores válidos está disponível em Lista de Timezones Suportados.

Valor Retornado

A função retorna FALSE se o timezone_identifier não é válido, ou TRUE caso contrário.

Exemplos

Exemplo #1 Lendo a timezone padrão

<?php
date_default_timezone_set
('America/Los_Angeles');

$script_tz date_default_timezone_get();

if (
strcmp($script_tzini_get('date.timezone'))){
    echo 
'Script timezone differs from ini-set timezone.';
} else {
    echo 
'Script timezone and ini-set timezone match.';
}
?>

Histórico

Versão Descrição
5.1.2 A função passou a validar o parâmetro timezone_identifier.

Veja Também



date_diff> <date_default_timezone_get
Last updated: Fri, 16 Jul 2010
 
User Contributed Notes
date_default_timezone_set
Dane Iracleous
21-Jul-2010 05:48
Here is some useful code to set the default timezone to the user's local timezone.

<?php
function getLocalTimezone()
{
   
$iTime = time();
   
$arr = localtime($iTime);
   
$arr[5] += 1900;
   
$arr[4]++;
   
$iTztime = gmmktime($arr[2], $arr[1], $arr[0], $arr[4], $arr[3], $arr[5], $arr[8]);
   
$offset = doubleval(($iTztime-$iTime)/(60*60));
   
$zonelist =
    array
    (
       
'Kwajalein' => -12.00,
       
'Pacific/Midway' => -11.00,
       
'Pacific/Honolulu' => -10.00,
       
'America/Anchorage' => -9.00,
       
'America/Los_Angeles' => -8.00,
       
'America/Denver' => -7.00,
       
'America/Tegucigalpa' => -6.00,
       
'America/New_York' => -5.00,
       
'America/Caracas' => -4.30,
       
'America/Halifax' => -4.00,
       
'America/St_Johns' => -3.30,
       
'America/Argentina/Buenos_Aires' => -3.00,
       
'America/Sao_Paulo' => -3.00,
       
'Atlantic/South_Georgia' => -2.00,
       
'Atlantic/Azores' => -1.00,
       
'Europe/Dublin' => 0,
       
'Europe/Belgrade' => 1.00,
       
'Europe/Minsk' => 2.00,
       
'Asia/Kuwait' => 3.00,
       
'Asia/Tehran' => 3.30,
       
'Asia/Muscat' => 4.00,
       
'Asia/Yekaterinburg' => 5.00,
       
'Asia/Kolkata' => 5.30,
       
'Asia/Katmandu' => 5.45,
       
'Asia/Dhaka' => 6.00,
       
'Asia/Rangoon' => 6.30,
       
'Asia/Krasnoyarsk' => 7.00,
       
'Asia/Brunei' => 8.00,
       
'Asia/Seoul' => 9.00,
       
'Australia/Darwin' => 9.30,
       
'Australia/Canberra' => 10.00,
       
'Asia/Magadan' => 11.00,
       
'Pacific/Fiji' => 12.00,
       
'Pacific/Tongatapu' => 13.00
   
);
   
$index = array_keys($zonelist, $offset);
    if(
sizeof($index)!=1)
        return
false;
    return
$index[0];
}

date_default_timezone_set(getLocalTimezone());
?>
Frederick Hathaway
04-Mar-2010 01:54
It's really a hassle that there is no way to set the timezone offset. I attempted to use the code that searched for the correct timezone name by offset from below. I found it didn't work reliably since various cities may have different rules about time DST etc. My solution is to actually search the array and do a test to insure the offset is what I expect it to be. It seems very kludgey (if thats a word) but it works.

<?php
function setTimezoneByOffset($offset)
    {
     
$testTimestamp = time();
       
date_default_timezone_set('UTC');
       
$testLocaltime = localtime($testTimestamp,true);
       
$testHour = $testLocaltime['tm_hour'];       

     
   
$abbrarray = timezone_abbreviations_list();
    foreach (
$abbrarray as $abbr)
    {
       
//echo $abbr."<br>";
     
foreach ($abbr as $city)
      {
               
date_default_timezone_set($city['timezone_id']);
               
$testLocaltime     = localtime($testTimestamp,true);
               
$hour                     = $testLocaltime['tm_hour'];       
               
$testOffset $hour - $testHour;
                if(
$testOffset == $offset)
                {
                    return
true;
                }
      }
    }
    return
false;
    }
?>
Christopher Kramer
09-Jan-2010 01:52
I experienced that using this function highly increases performance of functions like getdate() or date() using PHP 5.2.6 on Windows.
I experienced similar results on Linux servers with PHP 5.2.6 and 5.2.10, although the difference was not that significant on these servers: The PHP 5.2.10 server did run with date_default_timezone_set ("only") twice as fast as without. The 5.2.6 server did 5 times faster with date_default_timezone_set. As you can see below, the 5.2.6-Windows machine did a LOT faster.
Of course these machines have completely different hardware and can not really be compared, but all show improved performance.

I checked PHP 4.4.9 on Windows (without date_default_timezone_set of course) and noticed that its as fast as PHP 5.2.6 with date_default_timezone_set.

The following script shows this:

<?php

# uncomment to see difference
# date_default_timezone_set(date_default_timezone_get());

function getmicrotime()
 {
 list(
$usec, $sec) = explode(' ',microtime());
 return (
$sec.substr($usec,1,7));
 }
 
$start=mktime(0,0,0,1,1,2005);
$end=mktime(0,0,0,1,1,2020);
$nr=50000;
 
$start_time=getmicrotime();
for(
$i=0;$i<$nr;$i++) {
# $value=getdate(rand($start,$end));
 
date("H:i:s d.m.Y",rand($start,$end));
}
$end_time=getmicrotime();

echo
"Time: ".($end_time-$start_time);

// With date_default_timezone_set(): "Time: 0.379343986511"
// Without date_default_timezone_set(): "Time: 7.4971370697"

?>

Note that the timezone is not changed, it is only set again. I really wonder why this makes such a big performance difference, but its good to know.
ted dot chou12 at gmail dot com
03-Dec-2008 05:13
Timezone using other approaches:
<?php $datetime = strtotime($originaldatetime) + $time;
$datetime = date('M d, Y h:i A', $datetime);?>

$time obtained from table below:
-25200|International Date Line (West) GMT-12|
-21600|Midway Island, Samoa GMT-11|
-18000|Hawaii, Honolulu GMT-10|
-14400|Alaska GMT-9|
-10800|Pacific Standard Time, US, Canada GMT-8|
-7200|British Columbia N.E., Santa Fe, Mountain Time GMT-7|
-3600|Central America, Chicago, Guatamala, Mexico City GMT-6|
0|US, Canada, Bogota, Boston, New York GMT-5|
+3600|Canada, Santiago, Atlantic Standard Time GMT-4|
+7200|Brazilia, Buenos Aires, Georgetown, Greenland GMT-3|
+10800|Mid-Atlantic GMT-2|
+14400|Azores, Cape Verde Is., Western Africa Time GMT-1|
+18000|London, Iceland, Ireland, Morocco, Portugal GMT|
+21600|Amsterdam, Berlin, Bern, Madrid, Paris, Rome, GMT+1|
+25200|Athens, Cairo, Cape Town, Finland, Greece, Israel GMT+2|
+28800|Ankara, Aden, Baghdad, Beruit, Kuwait, Moscow GMT+3|
+32400|Abu Dhabi, Baku, Kabul, Tehran, Tbilisi, Volgograd GMT+4|
+36000|Calcutta, Colombo, Islamabad, Madras, New Dehli GMT+5|
+39600|Almaty, Dhakar, Kathmandu, Colombo, Sri Lanka GMT+6|
+43200|Bangkok, Hanoi, Jakarta, Phnom Penh, Australia GMT+7|
+46800|Taipei, Beijing, Hong Kong, Singapore, GMT+8|
+50400|Seoul, Tokyo, Central Australia GMT+9|
+54000|Brisbane, Canberra, Guam, Melbourne, Sydney, GMT+10|
+57600|Magadan, New Caledonia, Solomon Is. GMT+11|
+61200|Auckland, Fiji, Kamchatka, Marshall, Wellington, GMT+12|
jason at jasonpriem dot com
12-Nov-2008 02:29
While it's easy to change timezones based on names or abbreviations, I haven't found any straightforward way of doing so using an offset integer.  This situation comes up if you're using AJAX to get information about a user's timezone; javascript's getTimezoneOffset() method just sends you an offset number. So, here's my clunky solution: an adaptation of chris' function at http://us.php.net/manual/en/function.timezone-name-from-abbr.php.

<?php
   
function set_tz_by_offset($offset) {
       
$offset = $offset*60*60;
       
$abbrarray = timezone_abbreviations_list();
        foreach (
$abbrarray as $abbr) {
           
//echo $abbr."<br>";
               
foreach ($abbr as $city) {
                   
//echo $city['offset']." $offset<br>";
                       
if ($city['offset'] == $offset) { // remember to multiply $offset by -1 if you're getting it from js
                              
date_default_timezone_set($city['timezone_id']);
                               return
true;
                        }
                }
        }
   
date_default_timezone_set("ust");
       return
false;
       }

set_tz_by_offset(-1);

?>

[EDIT BY thiago AT php DOT net: This code has contributions from iateadonut at gmail dot com]
Anonymous
28-Sep-2008 02:34
If you have problems with errors, why the default is not set use this on the top of the script:

<?php
if(function_exists("date_default_timezone_set") and function_exists("date_default_timezone_get"))
@
date_default_timezone_set(@date_default_timezone_get());
?>
Rob Kaper
15-Jul-2008 05:46
If you want users to choose their own timezones, here's some code that gets all available timezones but only uses one city for each possible value:

<?php

$timezones
= DateTimeZone::listAbbreviations();

$cities = array();
foreach(
$timezones as $key => $zones )
{
    foreach(
$zones as $id => $zone )
    {
       
/**
         * Only get timezones explicitely not part of "Others".
         * @see http://www.php.net/manual/en/timezones.others.php
         */
       
if ( preg_match( '/^(America|Antartica|Arctic|Asia|Atlantic|Europe|Indian|Pacific)\//', $zone['timezone_id'] ) )
           
$cities[$zone['timezone_id']][] = $key;
    }
}

// For each city, have a comma separated list of all possible timezones for that city.
foreach( $cities as $key => $value )
   
$cities[$key] = join( ', ', $value);

// Only keep one city (the first and also most important) for each set of possibilities.
$cities = array_unique( $cities );

// Sort by area/city name.
ksort( $cities );

?>
PeerGoal.com
12-Feb-2007 10:21
The problem:

date() [function.date]: It is not safe to rely on the system's timezone settings. Please use the date.timezone setting, the TZ environment variable or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/Los_Angeles' for 'PST/-8.0/no DST' instead

Of course this is a problem that recently surfaced since PHP5. Quick fix is to set your time zone, add this line to your php code:

date_default_timezone_set("America/Los_Angeles");
davidn at datalinktech dot com dot au
21-Dec-2006 11:27
Note that there may be some unexpected side-effects that result from using either set_default_timezone() or the putenv("TZ=...") workalike for earlier PHP versions.  ANY date formatted and output either by PHP or its apache host process will be unconditionally expressed in that timezone.

[red. That is only true for the putenv() hack - Derick]

This does indeed include the web server's logs and other output files and reports which by default usually do not include any indication of timezone. This has a further side-effect on log processing and analysis, obviously.

date_diff> <date_default_timezone_get
Last updated: Fri, 16 Jul 2010