date_default_timezone_get

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

date_default_timezone_get Obtiene la zona horaria predeterminada usada por todas las funciones de fecha/hora en un script

Descripción

date_default_timezone_get(): string

En orden de preferencia, esta función devuelve la zona horaria predeternimada mediante:

  • Leer la zona horaria usando la función date_default_timezone_set() (si hay alguna)

  • Sólo antes de PHP 5.4.0: Leer la variable de entorno TZ (si no está vacía)

  • Leer el valor de la opción ini date.timezone (si está establecida)

  • Sólo antes de PHP 5.4.0: Preguntar al sistema operativo (siempre que el SO lo soporte y lo permita). Utiliza un algoritmo que debe estimar la zona horaria. No funcionará de forma necesariamente correcta en todas las situaciones posibles. Si se diera este caso, se mostrará una alerta. No se aconseja depender de esta función. En su lugar, debe establecerse la zona horaria correcta con date.timezone

Si nada de lo de arriba sucedió, date_default_timezone_get() devolverá una zona horaria predeterminada de UTC.

Valores devueltos

Devuelve un string.

Historial de cambios

Versión Descripción
5.4.0 La variable de entorno TZ ya no se usa para adivinar la zona horaria.
5.4.0 La zona horaria ya no se adivina de la información disponible a través del sistema operativo, la zona horaria adivinada no puede invocarse.

Ejemplos

Ejemplo #1 Obtener la zona horaria por defecto

<?php
date_default_timezone_set
('Europe/London');

if (
date_default_timezone_get()) {
echo
'date_default_timezone_set: ' . date_default_timezone_get() . '<br />';
}

if (
ini_get('date.timezone')) {
echo
'date.timezone: ' . ini_get('date.timezone');
}

?>

El resultado del ejemplo sería algo similar a:

date_default_timezone_set: Europe/London
date.timezone: Europe/London

Ejemplo #2 Obtener la abreviatura de una zona horaria

<?php
date_default_timezone_set
('America/Los_Angeles');
echo
date_default_timezone_get() . ' => ' . date('e') . ' => ' . date('T');
?>

El resultado del ejemplo sería:

America/Los_Angeles => America/Los_Angeles => PST

Ver también

add a note add a note

User Contributed Notes 8 notes

up
14
bohwaz
10 years ago
Please note that on Debian/Ubuntu this function will return the system timezone defined in /etc/localtime if date.timezone is not defined, even with PHP 5.4+

See http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=673763#10
up
1
smcbride at msn dot com
3 years ago
This function is not very useful for getting the OS timezone.  One way to do it is to look at the results of 'timedatectl' from the OS.  You can also look at the link from /etc/localtime

>file /etc/localtime
/etc/localtime: symbolic link to /usr/share/zoneinfo/America/Los_Angeles

>timedatectl
               Local time: Thu 2020-12-24 07:11:27 PST    
           Universal time: Thu 2020-12-24 15:11:27 UTC    
                 RTC time: Thu 2020-12-24 15:11:27        
                Time zone: America/Los_Angeles (PST, -0800)
System clock synchronized: yes                            
              NTP service: active                         
          RTC in local TZ: no

<?php

$dateinfo
= trim(shell_exec("timedatectl | grep -i zone: 2>/dev/null"));
$dateinfoarray = explode(' ', $dateinfo);
echo
'Timezone = ' . $dateinfoarray[2] . PHP_EOL;

?>
up
7
glennpratt+php at gmail dot com
12 years ago
In my case, I'm not sure I can guess the correct timezone any better than PHP and it's no where near important enough to nag the user, so...

<?php
// Suppress DateTime warnings
date_default_timezone_set(@date_default_timezone_get());
?>
up
2
andrea at -REMOVE- bhweb dot it
8 years ago
Please note that "Damien dot Garrido dot Work at gmail dot com" code is wrong, the third parameter of sprintf must be divided by 60.

This is the corrected function:

<?php
function timezone_offset_string( $offset )
{
        return
sprintf( "%s%02d:%02d", ( $offset >= 0 ) ? '+' : '-', abs( $offset / 3600 ), abs( $offset % 3600 ) / 60 );
}
?>
up
-1
Damien dot Garrido dot Work at gmail dot com
11 years ago
To get offset string from offset:

<?php

function timezone_offset_string( $offset )
{
        return
sprintf( "%s%02d:%02d", ( $offset >= 0 ) ? '+' : '-', abs( $offset / 3600 ), abs( $offset % 3600 ) );
}

$offset = timezone_offset_get( new DateTimeZone( 'Pacific/Kiritimati' ), new DateTime() );
echo
"offset: " . timezone_offset_string( $offset ) . "\n";

$offset = timezone_offset_get( new DateTimeZone( 'Pacific/Tahiti' ), new DateTime() );
echo
"offset: " . timezone_offset_string( $offset ) . "\n";
?>

Output:
offset: +14:00
offset: -10:00
up
-14
benrwhite at gmail dot com
10 years ago
For the reason that date_default_timezone_get() throws an error when the timezone isn't set in php.ini and then returns a default chosen by the system (rather than returning false to indicate to the script that a timezone hasn't been set), I've found that the following works when you want a script to detect when the ini value has not been set and want the script itself to choose a default in that case, while still allowing bootstrap scripts to set their own default using date_default_timezone_set().

<?php

set_error_handler
(function ($errno, $errstr){
    throw new
Exception($errstr);
    return
false;
});
try{
   
date_default_timezone_get();
}
catch(
Exception $e){
   
date_default_timezone_set('UTC'); // Sets to UTC if not specified anywhere in .ini
}
restore_error_handler();
up
-16
harmor
16 years ago
If you want to get the abbrivation (3 or 4 letter), instead of the long timezone string you can use date('T') function like this:

Input:
date_default_timezone_set('America/Los_Angeles');
echo date_default_timezone_get();
echo ' => '.date('e');
echo ' => '.date('T');

Output:
America/Los_Angeles => America/Los_Angeles => PST
up
-20
dohpaz at gmail dot com
16 years ago
date_default_timezone_get() will still emit a warning in E_STRICT if the timezone is not set; either by date_default_timezone_set() or the ini option of date.timezone.

This is probably not a big deal, but I thought I would contribute what I found.
To Top