php get default timezone

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.

    Источник

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

    Описание

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

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

      Только до версии PHP 5.4.0: чтение переменной окружения TZ (если она не пуста)

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

      Только до версии PHP 5.4.0: опрос операционной системы (если поддерживается и разрешено ОС). При этом используется механизм угадывания временной зоны. Этот механизм не всегда корректно работает. Если используется этот метод (все предыдущие не дали результата), будет выдано предупреждение. Не стоит полагаться на результат, полученный этим способом, вместо этого лучше задать в параметрах временной зоны date.timezone правильное значение.

      Если ни один из способов не принес результата, date_default_timezone_get() вернет временную зону UTC.

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

      Список изменений

      ВерсияОписание
      5.4.0Переменная окружения TZ больше не используется при угадывании временной зоны.
      5.4.0Временная зона больше не угадывается с помощью информации, полученной из операционной системы, так как данный метод нестабилен и на него нельзя полагаться.

      Примеры

      Пример #1 Получение временной зоны по умолчанию

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

      Пример #2 Получение аббревиатуры временной зоны

      Источник

      date_default_timezone_set

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

      date_default_timezone_set — Sets the default timezone used by all date/time functions in a script

      Description

      date_default_timezone_set() sets the default timezone used by all date/time functions.

      Instead of using this function to set the default timezone in your script, you can also use the INI setting date.timezone to set the default timezone.

      Parameters

      Return Values

      This function returns false if the timezoneId isn’t valid, or true otherwise.

      Examples

      Example #1 Getting the default timezone

      See Also

      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

      Иногда возникает такая ситуация, что текущее время на сервере не соответствует вашему текущему часовому поясу или часовому поясу региона, на который ориентирован ваш сайт.

      Чтобы было понятно, напомню: территориально Россия очень большая, и далеко не всем нужно, чтобы их сайты «жили» по московскому времени. Например, Урал, Сибирь, Дальний восток и т.д.

      Серверы большинства популярных российских хостинг-провайдеров размещены на технологических площадках Москвы и Санкт-Петербурга и по-умолочанию настроены, естественно, на московскую временну́ю зону. Сервер не может автоматически подстраиваться под ваше текущее местоположение и переводить системные часы. В связи с чем, работа функций даты и времени на сайте может быть не совсем корректной. Естественно, сейчас речь не идёт о CMS, в которых поправка часового пояса обычно присутствует прямо в интерфейсе администратора.

      В первую очередь проверьте текущее состояние с помощью PHP-кода:

      Хорошо, если у вас свой сервер и имеется доступ к php.ini, где можно задать нужную временну́ю зону и забыть. Например, таким образом:

      Правда, если на сервере размещены несколько проектов, в которых должны поддерживаться различные часовые пояса, тогда лучше этого не делать. В этом случае будет правильнее задать временные зоны только для проектов, где один часовой пояс.

      Установка временной зоны на виртуальном хостинге

      Если способ не сработает, тогда воспользуемся функцией date_default_timezone_set(), которая устанавливает временную зону по умолчанию для всех функций даты и времени. Для этого нужно где-нибудь в начале скрипта просто добавьте такую строку:

      Естественно, Europe/Moscow меняется на необходимый вам часовой пояс. Для территории РФ в PHP поддерживаются следующие временные зоны:

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

      Делаю сайты на Вордпресс с 2008 года, занимаюсь их оптимизацией, беру на поддержку, делюсь опытом в блоге и соцсетях (ссылки ниже, подпишитесь)

      Источник

      How to get local time in php?

      I am trying to get the local time using php. I wrote two different versions, but they both give the wrong time

      In both cases I get the time 4 fours ahead of my local time. There is any other way to get the local time?

      php get default timezone. Смотреть фото php get default timezone. Смотреть картинку php get default timezone. Картинка про php get default timezone. Фото php get default timezone

      7 Answers 7

      DateTime::getTimestamp() returns unix timestamp. That number is always UTC. What you want is format the date according to your time zone.

      Or use a different date format, according to what you need.

      Also, you can use DateTime library for all your date needs. No need to change server’s default timezone every time you want to fetch the date.

      php get default timezone. Смотреть фото php get default timezone. Смотреть картинку php get default timezone. Картинка про php get default timezone. Фото php get default timezone

      Simply use function date_default_timezone_set(). Here is example:

      Hope it will help, Thanks.

      php get default timezone. Смотреть фото php get default timezone. Смотреть картинку php get default timezone. Картинка про php get default timezone. Фото php get default timezone

      You need to use javascript because you want the value of time from the client. PHP is a server-side language that evaluates on the server and sends results to the client. So if you try to pull a date/time using a PHP function, it’s going to pull the date from the server, which is not always in the client’s timezone.

      You can do this in a javascript function and then reference the value in the display.

      var thisDateTime = new Date();

      I’m wondering why nobody has mentioned localtime(time()); in PHP with indexed key array result or localtime(time(), true); with associative key array result.

      php get default timezone. Смотреть фото php get default timezone. Смотреть картинку php get default timezone. Картинка про php get default timezone. Фото php get default timezone

      If you don’t want to use timezone you can use this mix of windows and php commands:

      php get default timezone. Смотреть фото php get default timezone. Смотреть картинку php get default timezone. Картинка про php get default timezone. Фото php get default timezone

      You can solve this problem by using localtime() function or through date_default_timezone_set() function.

      i think this must help you..

      php get default timezone. Смотреть фото php get default timezone. Смотреть картинку php get default timezone. Картинка про php get default timezone. Фото php get default timezone

      For the record, I found the only solution to read the real hour of the machine is to read the information outside of PHP (javascript, shell or other processes). Why?

      For example, let’s say we have an hour based in daily-saving. What if the timezone of the OS (Windows in my case) is not in sync with the timezone of PHP, I mean, it could be calculated differently. Or maybe the machine is using a different hour and it is ignoring the daily-saving hour.

      php get default timezone. Смотреть фото php get default timezone. Смотреть картинку php get default timezone. Картинка про php get default timezone. Фото php get default timezone

      Not the answer you’re looking for? Browse other questions tagged php or ask your own question.

      Linked

      Related

      Hot Network Questions

      Subscribe to RSS

      To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

      site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238

      By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

      Источник

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

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