- Date default timezone set не работает
- Сообщение об ошибке date.timezone в PHP последних версий
- date_default_timezone_set — Ошибка
- Описание
- Список параметров
- Возвращаемые значения
- Примеры
- Список изменений
- Смотрите также
- date_default_timezone_set
- Описание
- Список параметров
- Возвращаемые значения
- Примеры
- Смотрите также
- User Contributed Notes 22 notes
Date default timezone set не работает
БлогNot. Сообщение об ошибке date.timezone в PHP последних версий
Сообщение об ошибке date.timezone в PHP последних версий
Маленький ответ на маленький вопрос. PHP последних версий довольно строг в отношении вывода сообщений об ошибках и предупреждений, скорее всего, в Вашем файле настроек стоит
Это, в частности, означает, что вывод предупреждений (Warnings, директива E_WARNING ) не подавлен, поэтому при ненастроенном «часовом поясе по умолчанию» каждый вызов функции date(. ) , в котором не подавлен вывод ошибок ( @date(. ) ), да и другие собщения об ошибках будут сопровождаться предупреждением вида
Просто поставьте в активном файле php.ini настройку date.timezone в секции [DATE] , например:
для часового пояса GMT+6 — если лень искать в списках свой город. — не надо так делать, всё-таки значение зоны из спецификации; а вот без кавычек можно:
Узнать, откуда подключён файл настроек php.ini, можно, выполнив это:
Ответ содержится в первой таблице в строке Loaded Configuration File
Начиная с PHP 5.1.0 можно установить временную зону по умолчанию для всех функций скрипта и без правки файла php.ini — для этого достаточно вызвать метод date_default_timezone_set с параметром-идентификатором временной зоны (см. ссылку выше).
Например, для Новосибирска делаем так:
Ещё лучше предусмотреть в скрипте соответствующую настройку.
Ещё я делаю так где-нибудь в начале скрипта (лучше всего в коде, выполняющемся 1 раз):
Источник
date_default_timezone_set — Ошибка
(PHP 5 >= 5.1.0, PHP 7)
date_default_timezone_set — Устанавливает временную зону по умолчанию для всех функций даты/времени в скрипте
Описание
date_default_timezone_set() устанавливает временную зону по умолчанию для всех функций даты/времени в скрипте .
Начиная с версии PHP 5.1.0 (когда функции даты/времени были переписаны), вызов любой функции даты времени генерирует E_NOTICE , если временная зона имеет неверное значение, и/или E_WARNING , если используются системные параметры или переменная окружения TZ .
Вместо использования этой функции, Вы можете воспользоваться INI настройкой date.timezone для установки временной зоны по умолчанию.
Список параметров
Идентификатор временной зоны, как например UTC или Europe/Lisbon. Список поддерживаемых временных зон.
Возвращаемые значения
Функция возвращает FALSE , если timezone_identifier имеет неверное значение, в остальных случаях TRUE .
Примеры
Пример #1 Получение временной зоны по умолчанию
if ( strcmp ( $script_tz , ini_get ( ‘date.timezone’ ))) <
echo ‘Временная зона скрипта отличается от заданной в INI-файле.’ ;
> else <
echo ‘Временные зоны скрипта и настройки INI-файла совпадают.’ ;
>
?>
Список изменений
| Версия | Описание |
|---|---|
| 5.3.0 | Теперь выбрасывает E_WARNING вместо E_STRICT . |
| 5.1.2 | Функция начала проверять timezone_identifier . |
Смотрите также
- date_default_timezone_get() — Возвращает временную зону, используемой по умолчанию всеми функциями даты/времени в скрипте
- Список поддерживаемых временных зон
Источник
date_default_timezone_set
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
date_default_timezone_set — Устанавливает часовой пояс по умолчанию для всех функций даты/времени в скрипте
Описание
date_default_timezone_set() устанавливает часовой пояс по умолчанию для всех функций даты/времени в скрипте.
Вместо использования этой функции, вы можете воспользоваться INI-настройкой date.timezone для установки часового пояса по умолчанию.
Список параметров
Идентификатор часового пояса, например, UTC , Africa/Lagos , Asia/Hong_Kong или Europe/Lisbon . Список допустимых идентификаторов часовых поясов можно найти в разделе Список поддерживаемых часовых поясов.
Возвращаемые значения
Функция возвращает false , если timezoneId имеет неверное значение, в остальных случаях true .
Примеры
Пример #1 Получение часового пояса по умолчанию
if ( strcmp ( $script_tz , ini_get ( ‘date.timezone’ ))) <
echo ‘Часовой пояс скрипта отличается от заданного в INI-файле.’ ;
> else <
echo ‘Часовой пояс скрипта и настройки INI-файла совпадают.’ ;
>
?>
Смотрите также
- date_default_timezone_get() — Возвращает часовой пояс, используемый по умолчанию всеми функциями даты/времени в скрипте
- Список поддерживаемых часовых поясов
User Contributed Notes 22 notes
I’m sure I’m not the only one who is distressed by the recent default behavior change to E_NOTICE when the timezone isn’t explicitly set in the program or in .ini. I insure that the clock on the server IS correct, and I don’t want to have to set it in two places (the system AND PHP). So I want to read it from the system. But PHP won’t accept that answer, and insists on a call to this function. So, here’s my answer:
function setTimezone ( $default ) <
$timezone = «» ;
// On many systems (Mac, for instance) «/etc/localtime» is a symlink
// to the file with the timezone info
if ( is_link ( «/etc/localtime» )) <
// If it is, that file’s name is actually the «Olsen» format timezone
$filename = readlink ( «/etc/localtime» );
$pos = strpos ( $filename , «zoneinfo» );
if ( $pos ) <
// When it is, it’s in the «/usr/share/zoneinfo/» folder
$timezone = substr ( $filename , $pos + strlen ( «zoneinfo/» ));
> else <
// If not, bail
$timezone = $default ;
>
>
else <
// On other systems, like Ubuntu, there’s file with the Olsen time
// right inside it.
$timezone = file_get_contents ( «/etc/timezone» );
if (! strlen ( $timezone )) <
$timezone = $default ;
>
>
date_default_timezone_set ( $timezone );
>
?>
Use it by calling it with a fallback default answer.
Yes, I know it doesn’t work on Windows. Neither do I 🙂 Perhaps someone wants to add that functionality.
Hope this helps someone.
As Christopher Kramer said 9 years ago, not setting default timezone has performance impacts on PHP 5.6, and on PHP 7.1
It hasn’t on php 7.2 anymore.
As I set error_reporting to 0 in my script, it doesn’t seem linked to the fact it is logging the error.
I ran its benchmark script (modified) on Linux multiple times, alternating ‘on’ and ‘off’ setting :
$tz = ( $argc > 1 && ( $argv [ 1 ] == ‘on’ )) ? ‘on’ : ‘off’ ;
if ( $tz == ‘on’ ) date_default_timezone_set (@ date_default_timezone_get ());
$start = mktime ( 0 , 0 , 0 , 1 , 1 , 2005 );
$end = mktime ( 0 , 0 , 0 , 1 , 1 , 2020 );
$t0 = microtime ( true );
for ( $i = 0 ; $i 50000 ; $i ++) date ( «H:i:s d.m.Y» , rand ( $start , $end ));
echo «Time ( $tz ): » .(( microtime ( true ) — $t0 )* 100 ). «\n» ;
This creates a huge problem for downloadable programs, which obviously cannot be hardcoded as this suggests, since the coder has no idea where they will be run.
Seems to me that if the server’s timezone cannot be relied on, then THAT is the the problem which needs fixed. Not, cause the coder’s syntactically-correct work to generate bogus error messages.
> I’m sure I’m not the only one who is distressed by the recent default behavior change to E_NOTICE when the timezone isn’t explicitly set in the program or in .ini.
You should always turn on notices and have a customer error handler that converts notices or indeed any PHP message to exceptions.
I’ve been doing this for years and it looks like expanding the use of exceptions in PHP itself is an ongoing process. It’s almost certainly stuck with notices from legacy patterns prior to PHP possessing exception capability with the reason it’s not been thoroughly applied being BC breakage.
Even in my extensions I redirect notices and warnings to exceptions. I’m certain the whole pressure for the ?? operator was to facilitate errors to exceptions as the only real drawback of that is needing to use isset a fair bit more.
Similar for asserts, json, etc, etc it all to use exceptions.
Another note. I profiled my PHP script and it reported that calling this function took half the time. Anyone else got this? Is it really that expensive? Am I doubling init time not having it in php.ini and possibly setting to the timezone it’s already on? Or is it messing with time and breaking the time measurement? One day I’ll bother to wrap it in microtime to try to see.
After poundering and knocking my head on the table, I finally got a proper fix for Windows and PHP timezone handling.
Since Windows applies the DST to ActiveTimeBias in the registry, you only need this to apply.
The only problem is, that it cant use the timezone_set command.
You can request a response back in any date-format you wish, or use the default one given in the function itself.
// Return proper time
function time_zone_fix ( $timeGiven = «H:i:s» )
<
$shell = new COM ( «WScript.Shell» ) or die( «Requires Windows Scripting Host» );
$time_bias = -( $shell -> RegRead ( «HKEY_LOCAL_MACHINE\\SYSTEM\\
CurrentControlSet\\Control\\TimeZoneInformation\\
ActiveTimeBias» )) / 60 ;
$timestamp_bias = 60 * 60 * $time_bias ;
echo $time_bias . «
» ;
return gmdate ( $timeGiven , strtotime ( $timestamp_bias . » seconds» ));
>
?>
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:
$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 );
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:
# 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.
I found a need to change the timezone based on a DB record, so it would display properly for each record. So I wrapped some of the other posts into this small class:
class TZStack
<
private $stack = array();
public function __construct ()<>
public function push ( $newTZ )
<
array_push ( $this -> stack , date_default_timezone_get ());
if (isset( $newTZ ) && ( «» != $newTZ ))
<
date_default_timezone_set ( $newTZ );
>
>
public function pop ()
<
if ( count ( $this -> stack ) > 0 )
<
date_default_timezone_set ( array_pop ( $this -> stack ));
>
>
>
// the global TZ stack for the rest of the code to use.
$tzStack = new TZStack ();
// In case I need to know the TZ at the web server. 🙂
$script_tz = date_default_timezone_get ();
?>
Then in my per-record code:
foreach( $records as $item )
<
$tzStack -> push ( $item [ ‘TZ’ ]);
$TZ = date ( «T» , time ());
// code that displays this record, using $TZ.
$tzStack -> pop ();
>
?>
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() [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:
I was having major issues with the date.timezone setting after I updated from 5.3.3 to 5.4.29. I still need to update further, and perhaps it’s a bug in this version that will be fixed when I update..
But to fix the issue of php not being about to find my time zone, I added a .htaccess file to the root of my web directory. All I have in it is this one line (without quotes)
«php_value date.timezone America/Denver»
And now the timezone is set in any directory I browse in. Very strange, and I still haven’t figured out why It wont work from the php.ini file. But here’s how to overcome the frustration.
This is a good script if you know or control your system so that you know that the local TZ in your OS is correct. Unfortunately, this script still creates an warning message under BSD UNIX.
To fix this, just add an «@» in front of «localtime» as:
Источник