установить временную зону php

Временные зоны и часовые пояса в PHP

Со временем каждый проект расширяется, одного региона становится мало. Часто посетителю нужно показать время его часового пояса.

date_default_timezone_set — устанавливаем временную зону по умолчанию для всех функций даты/времени в скрипте

Код PHP

Для того, чтобы пользователь на сайте видел время своего часового пояса, можно использовать средства PHP. Пользователю предоставляем выбор (select) его часового пояса, заносим результат в переменную и БД, а переменную в аргумент встроенной функции date_default_timezone_set.
В результате время его сообщений, объявлений, заказов будет отображаться согласно его временной зоне. Можно, конечно, обойтись и средствами JavaScript на клиенте, но будет проблема с теми, у кого работа js блокируется Браузером.

Примеры часовых поясов для PHP

Часть временных зон подписал, чтобы сразу можно было найти нужную. В скрипт вставлять соответственно Часть света/Город, например, Europe/Minsk.

Европа

Europe/Amsterdam (Амстердам, Нидерланды)
Europe/Andorra
Europe/Athens (Афины, Греция)
Europe/Belfast (Белфаст, Северная Ирландия)
Europe/Belgrade (Белград, Сербия)
Europe/Berlin (Берлин, Германия)
Europe/Bratislava (Братислава, Словакия)
Europe/Brussels (Брюссель, Бельгия)
Europe/Bucharest (Бухарест, Румыния)
Europe/Budapest (Будапешт, Венгрия)
Europe/Chisinau
Europe/Copenhagen (Копенгаген, Дания)
Europe/Dublin (Дублин, Ирландия)
Europe/Gibraltar
Europe/Guernsey
Europe/Helsinki (Хельсинки, Финляндия)
Europe/Isle_of_Man
Europe/Istanbul (Стамбул, Турция)
Europe/Jersey
Europe/Kaliningrad (Калининград, Россия)
Europe/Kiev (Киев, Украина)
Europe/Lisbon (Лиссабон, Португалия)
Europe/Ljubljana (Любляна, Словения)
Europe/London (Лондон, Великобритания)
Europe/Luxembourg
Europe/Madrid (Мадрид, Испания)
Europe/Malta (Мальта, Мальта)
Europe/Mariehamn
Europe/Minsk (Минск, Беларусь)
Europe/Monaco
Europe/Moscow (Москва, Россия)
Europe/Nicosia (Никосия, Кипр)
Europe/Oslo (Осло, Норвегия)
Europe/Paris (Париж, Франция)
Europe/Podgorica
Europe/Prague (Прага, Чехия)
Europe/Riga (Рига, Латвия)
Europe/Rome (Рим, Италия)
Europe/Samara (Самара, Россия)
Europe/San_Marino
Europe/Sarajevo (Сараево, Босния и Герцеговина)
Europe/Simferopol
Europe/Skopje (Скопье, Македония)
Europe/Sofia (София, Болгария)
Europe/Stockholm
Europe/Tallinn (Таллин, Эстония)
Europe/Tirane
Europe/Tiraspol (Тирасполь, Молдова)
Europe/Uzhgorod (Ужгород, Украина)
Europe/Vaduz
Europe/Vatican
Europe/Vienna (Вена, Австрия)
Europe/Vilnius (Вильнюс, Литва)
Europe/Volgograd (Волгоград, Россия)
Europe/Warsaw (Варшава, Польша)
Europe/Zagreb (Загреб, Хорватия)
Europe/Zaporozhye (Запорожье, Украина)
Europe/Zurich (Цюрих, Швейцария)

Азия

Asia/Aden
Asia/Almaty
Asia/Amman
Asia/Anadyr (Анадырь, Россия)
Asia/Aqtau (Актау, Казахстан)
Asia/Aqtobe (Актобе, Казахстан)
Asia/Ashgabat
Asia/Ashkhabad (Ашхабад, Туркменистан)
Asia/Baghdad (Багдад, Ирак)
Asia/Bahrain
Asia/Baku (Баку, Азербайджан)
Asia/Bangkok
Asia/Beirut
Asia/Bishkek (Бишкек, Киргизия)
Asia/Brunei
Asia/Calcutta
Asia/Choibalsan
Asia/Chongqing
Asia/Chungking
Asia/Colombo
Asia/Dacca (Дакка, Бангладеш)
Asia/Damascus
Asia/Dhaka
Asia/Dili
Asia/Dubai
Asia/Dushanbe
Asia/Gaza
Asia/Harbin (Харбин, Китай)
Asia/Hebron
Asia/Ho_Chi_Minh
Asia/Hong_Kong (Гонконг, Китай)
Asia/Hovd
Asia/Irkutsk (Иркутск, Россия)
Asia/Istanbul
Asia/Jakarta (Джакарта, Индонезия)
Asia/Jayapura
Asia/Jerusalem
Asia/Kabul (Кабул, Афганистан)
Asia/Kamchatka
Asia/Karachi
Asia/Kashgar
Asia/Kathmandu
Asia/Katmandu
Asia/Khandyga
Asia/Kolkata
Asia/Krasnoyarsk
Asia/Kuala_Lumpur
Asia/Kuching
Asia/Kuwait
Asia/Macao
Asia/Macau
Asia/Magadan
Asia/Makassar
Asia/Manila
Asia/Muscat
Asia/Nicosia
Asia/Novokuznetsk (Новокузнецк, Россия)
Asia/Novosibirsk
Asia/Omsk (Омск, Россия)
Asia/Oral (Уральск, Казахстан)
Asia/Phnom_Penh
Asia/Pontianak
Asia/Pyongyang
Asia/Qatar
Asia/Qyzylorda
Asia/Rangoon
Asia/Riyadh
Asia/Saigon (Сайгон, Вьетнам)
Asia/Sakhalin (Сахалин, Россия)
Asia/Samarkand (Самарканд, Узбекистан)
Asia/Seoul (Сеул, Южная Корея)
Asia/Shanghai (Шанхай, Китай)
Asia/Singapore (Сингапур, Сингапур)
Asia/Taipei
Asia/Tashkent (Ташкент, Узбекистан)
Asia/Tbilisi (Тбилиси, Грузия)
Asia/Tehran
Asia/Tel_Aviv (Тель-Авив, Израиль)
Asia/Thimbu
Asia/Thimphu
Asia/Tokyo (Токио, Япония)
Asia/Ujung_Pandang
Asia/Ulaanbaatar
Asia/Ulan_Bator (Улан-Батор, Монголия)
Asia/Urumqi
Asia/Ust-Nera (Усть-Нера, Россия)
Asia/Vientiane (Вьетьян, Лаос)
Asia/Vladivostok (Владивосток, Россия)
Asia/Yakutsk (Якутск, Россия)
Asia/Yekaterinburg (Екатеринбург, Россия)
Asia/Yerevan (Ереван, Армения)

Источник

date_default_timezone_get

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

date_default_timezone_get — Возвращает часовой пояс, используемый по умолчанию всеми функциями даты/времени в скрипте

Описание

Функция пытается получить часовой пояс по умолчанию по порядку следующими способами:

    Чтение настройки часового пояса с помощью функции date_default_timezone_set() (если применимо)

    Чтение значения ini-настройки date.timezone (если задана)

    Если используется этот метод (все предыдущие не дали результата), будет выдано предупреждение. Не стоит полагаться на результат, полученный этим способом, вместо этого лучше задать в параметрах часового пояса date.timezone правильное значение.

    Список параметров

    У этой функции нет параметров.

    Возвращаемые значения

    Возвращает строку ( string ).

    Примеры

    Пример #1 Получение часового пояса по умолчанию

    Результатом выполнения данного примера будет что-то подобное:

    Пример #2 Получение аббревиатуры часового пояса

    Результат выполнения данного примера:

    Смотрите также

    User Contributed Notes 8 notes

    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+

    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

    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.

    // Suppress DateTime warnings
    date_default_timezone_set (@ date_default_timezone_get ());
    ?>

    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:

    To get offset string from offset:

    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().

    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

    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.

    Источник

    DateTime::setTimezone

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

    Описание

    Список параметров

    Возвращаемые значения

    Возвращает объект DateTime для связывания методов.

    Примеры

    Пример #1 Пример использования DateTime::setTimeZone()

    Результат выполнения данных примеров:

    Смотрите также

    User Contributed Notes 6 notes

    In response to the other comments expressing surprise that changing the timezone does not affect the timestamp:

    A UNIX timestamp is defined as the number of seconds that have elapsed since 00:00:00 (UTC), Thursday, 1 January 1970.

    So: with respect to UTC. Always.

    Calling setTimezone() never changes the actual «absolute», underlying, moment-in-time itself. It only changes the timezone you wish to «view» that moment «from». Consider the following:

    The timestamp value represented by the DateTime object is not modified when you set the timezone using this method. Only the timezone, and thus the resulting display formatting, is affected.

    This can be seen using the following test code:
    = new DateTimeZone ( ‘America/Denver’ );
    $ESTTZ = new DateTimeZone ( ‘America/New_York’ );

    = new DateTimeZone ( ‘America/Denver’ );
    $ESTTZ = new DateTimeZone ( ‘America/New_York’ );

    It appears that what forzi at mail333 dot com said is correct.

    In any case, other output values from format() seem to be accurate, and the true timestamp is always accessible via getTimestamp().

    I found unexpected behaviour when passing a timestamp.
    timezone seems to always be GMT+0000 unless setTimezone() is set.

    = new DateTimeZone ( ‘America/Denver’ );
    $ts = 1336476757 ;

    /** Output:
    string(8) «GMT+0000»
    string(10) «1336476757»
    string(3) «MDT»
    string(10) «1336476757»
    **/

    Источник

    date_default_timezone_set

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

    date_default_timezone_set — Устанавливает часовой пояс по умолчанию для всех функций даты/времени в скрипте

    Описание

    date_default_timezone_set() устанавливает часовой пояс по умолчанию для всех функций даты/времени в скрипте.

    Вместо использования этой функции, вы можете воспользоваться INI-настройкой date.timezone для установки часового пояса по умолчанию.

    Список параметров

    Возвращаемые значения

    Примеры

    Пример #1 Получение часового пояса по умолчанию

    Смотрите также

    User Contributed Notes 22 notes

    // 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» );

    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 :

    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.

    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.

    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.

    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:

    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());

    // 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:

    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.

    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..

    «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:

    Источник

    Правильный взгляд на временные зоны в PHP

    Это небольшая статья о том, как работать с временными зонами при хранении значений даты / времени в базе данных. Базы данных или язык программирования, который вы решите использовать, решающего значения не имеет, так как описываемые в статье явления универсальны. Свои действия я буду показывать на примере использования связки MySQL и PHP. Проблема, связанная с временными зонами, достаточно банальна. Многие часто забывают об их существовании, а некоторые считают их чем-то чрезмерно сложным. Обычно при настройке базы данных или при пользовании услугами веб-хостинга ваши временные зоны настроены по умолчанию. Настройки по умолчанию подойдут, если вы работаете с одним сервером, но что произойдет, если вы решите переместить его?

    Тот же вопрос закономерен, если у вас несколько серверов в разных местах.
    Вместо того чтобы хранить временные зоны с указанием каждой даты, лучше взять за основу стандартное время и связать все ваши даты с ним. Такой способ позволяет сделать переход на стандартное время до того, как значение будет сохранено в базе данных. Вообще, хорошая идея — просто использовать UTC +00:00.

    Что такое UTC

    Хранение времени в формате UTC +00:00

    Первое, что мы должны сделать, — определиться, какую временную зону использовать для хранения всех наших значений. Я настоятельно рекомендую взять за основу UTC +00:00 — без особой причины, кроме как той, что ее легко запомнить и 0 представляет собой идеальную точку отсчета. Так как мы знаем, что все даты указаны в UTC +00:00, становится гораздо легче представлять надлежащее время для каждого пользователя на основе их личных временных зон. После того как пользователь выбрал (или у нас есть автоопределение) свой часовой пояс, вывод соответствующего времени для этого пользователя становится обычным делом.

    Установка временной зоны по умолчанию

    Полагая, что все наши даты / время хранятся в формате UTC, мы можем просто установить по умолчанию временную зону, которая будет использоваться для отображения каждого времени. Это позволит автоматически подобрать дату и время для конкретного пользователя. В PHP все, что нам нужно сделать, — это установить временную зону, например, так:

    Мы можем сделать это в каком-нибудь блоке инициализации в начале нашего кода — и все готово: все даты будут отображаться надлежащим образом для того часового пояса, в котором находится пользователь.

    Если мы хотим получить полный контроль над датой и временем, мы можем построить функцию следующим образом:

    Настройка PHP под UTC +00:00

    Конечно, все было бы не так просто, если бы мы не настроили нашу систему под UTC, как временную зону по умолчанию. Я уверен, что это может быть сделано примерно одинаково и в других языках, но PHP это делается следующим образом:

    Теперь всякий раз, когда мы используем такие вещи, как, например, функцию time(), это автоматически дает нам время в формате UTC с соответствующим смещением на основе нашего серверного времени. Если мы захотим настроить даты, в такой базе данных как MySQL, сделаем так:

    Если у нас не было доступа к изменению конфигурации PHP, то мы должны настроить время вручную при установке даты, вот так:

    Настройка MySQL под UTC +00:00

    Непосредственная установка даты, как мы делали выше, применима, если у нас нет доступа к изменению параметров конфигурации MySQL. Тем не менее, если мы хотим использовать TIMESTAMP, которая обычно самообновляется, или такую функцию даты из MySQL, как NOW(), то мы должны настроить MySQL для использования UTC в качестве временной зоны по умолчанию.

    В MySQL это делается путем установки UTC смещения, которое может быть сделано так же легко, как это было в PHP, путем внесения следующих изменений:

    Обновление существующих дат / времени

    Если вы решили стандартизировать временные зоны при помощи UTC, где временной зоной по умолчанию является UTC +00:00 смещение, то теперь ваш текущее время в вашей базе данных будет неработоспособно.

    К счастью, MySQL предоставляет удобную функцию, которая дает нам возможность легко обновлять существующие часовые пояса.

    ПРИМЕЧАНИЕ: Если у вас есть какие-нибудь временные метки, то их нужно обновить в первую очередь.

    Мы можем осуществлять поиск по всем полям даты и времени в нашей базе с помощью следующего запроса:

    Отсюда мы можем использовать следующий запрос, чтобы обновить даты / время в наших таблицах:

    Где -05:00 — текущая временная зона, в формате которой хранится время (она как и в предыдущем случае относится к Восточной). Временная зона +00:00, в которую мы хотим преобразовать, в данном случае относится к UTC.

    Читайте также

    Стандартные библиотеки PHP умеют генерировать только целые случайные числа. Однако, возникают задачи где нужно не целое рандомное число с максимально…

    Казалось бы http_build_query — простая функция, однако, имеет некоторые особенности. Нельзя однозначно сказать что это баг, скорее просто недокументированная фича,…

    Иногда при обработке с помощью PHP больших и не очень данных, можно словить досадную ошибку посреди выполнения скрипта: PHP Fatal…

    Источник

    Добавить комментарий

    Ваш адрес email не будет опубликован. Обязательные поля помечены *