php get timezone date
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.
Get all timezones
I am trying to get all the timezones. What I have done is:
It gives me an array like this:
I want to change the timezone name to full timezone name for all timezones e.g.
You can see the example here
2 Answers 2
Though many will change throughout the year for daylight saving. If you want to check for this and add the alternate daylight/summer display name you can do something like:
What you are asking are IDs of Microsoft Windows time zones (here). PHP uses IANA/Olson time zones. See the timezone tag wiki for details.
Here another SO question that you can look, there are lots of similar answers: Generating a drop down list of timezones with PHP
If none of this helps, you can try the above code, to convert the data to your timezone. For example let us assume we have a UTC date and time string (2017-08-05 02:45) that we would like to convert to ACST (Australian Central Standard Time).
UPDATE:
From here, you have a Windows ids timezone to PHP:
AUS Central Standard Time,1,Australia/Darwin AUS Central Standard Time,AU,Australia/Darwin AUS Eastern Standard Time,1,Australia/Sydney AUS Eastern Standard Time,AU,Australia/Melbourne AUS Eastern Standard Time,AU,Australia/Sydney
change to a php array:
and then you can make a function to translate your timezone (array position 2) with your desired windows id (array position[0]), with find or whatever you want.
It’s a not the more elegant solution I guess but it will work and its simple. You can search over the array and return the required translation from one codification to the other.
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 Получение аббревиатуры временной зоны
The DateTimeZone class
(PHP 5 >= 5.2.0, PHP 7, PHP 8)
Introduction
Representation of time zone.
Class synopsis
Predefined Constants
DateTimeZone::AMERICA
America time zones.
DateTimeZone::ANTARCTICA
Antarctica time zones.
DateTimeZone::ARCTIC
DateTimeZone::ASIA
DateTimeZone::ATLANTIC
Atlantic time zones.
DateTimeZone::AUSTRALIA
Australia time zones.
DateTimeZone::EUROPE
DateTimeZone::INDIAN
DateTimeZone::PACIFIC
Pacific time zones.
DateTimeZone::UTC
DateTimeZone::ALL
DateTimeZone::ALL_WITH_BC
All time zones including backwards compatible.
DateTimeZone::PER_COUNTRY
Time zones per country.
Table of Contents
User Contributed Notes 2 notes
Seems like a significant differences between php 5.3 and 5.6:
It seems like as of PHP 5.5, creating a new DateTimeZone with a string like ‘EDT’ will cause DateTimeZone::getName() to return ‘EDT’ whereas prior to 5.5 it would convert it would have returned ‘America/New_York’
This is of particular note when using a DateTimeZone object to change the timezone on a DateTime object. Using a DateTimeZone object when set as shown above will cause the conversion to be wrong without throwing any errors.
Различные часовые пояса PHP на одной странице
Введение
Часто возникает необходимость отобразить время разных часовых поясов на одной странице.
Например, на сайте HeiHei.ru это сделано для того, чтобы те, кто едет в Финляндию видели одновременно и финское и московское время.
Отвечает за это команда
В этой статье Вы узнаете о том как показать время сразу нескольких зон одновременно на одной странице.
Более простые примеры вы можете изучить в статье
Показать московское время
Если у вас время по умолчанию московское просто выведите его
Если время не московское, то его нужно сделать московским
За смену часового пояса отвечает функция date_default_timezone_set()
date_default_timezone_set (
‘Europe/Moscow’ );
echo (date(«H:i:s»));
Пример кода на PHP
Теперь разберём случай когда нужно показать время сразу нескольких поясов на одной странице.
‘; date_default_timezone_set ( ‘Europe/Helsinki’ ); echo ‘
‘; date_default_timezone_set ( ‘Europe/Stockholm’ ); echo ‘
‘; date_default_timezone_set ( ‘Europe/Moscow’ ); echo ‘
Результат
Московское время 05:51:03
Время в Хельсинки 05:51:03
Время в Стокгольме 04:51:03
Комментарии к коду
Получаем зону, которая стоит по умолчанию на сервере.
Выводим её. И думаем, нужна нам эта зона или нет.
В следующей строке переменной moscow_time присвоено значение сервеного времени.
Отобразили московское время.
Теперь нужно изменить временную зону
Присвоить переменной helsinki_time значение
В конце, на всякий случай сделаем время по умолчанию снова московским.
DateTimeImmutable: пример с ООП
Если вы немного знакомы с ООП, проще будет создать три объекта DateTimeImmutable и использовать их.
В Армении: 06:51:03
В Норвегии: 04:51:03
В Испании: 04:51:03
Как обновить время
PHP отдает время при загрузке и не может его менять на отданной странице.
button » value=» Обновить страницу 1 » onClick=» location.href=location.href «>
button » value=» Обновить страницу 2 » onClick=» window.location.href=window.location.href «>
Результат
Оба этих варианта могут испытывать (а могут и не испытывать) проблемы в случае когда Вы перешли внутри страницы по якорю.
В этом случае попробуйте
Обновить страницу 3
Обновить страницу 3
Время в разных поясаха в данный момент
Во Владивостоке | 12:51:03 |
В Токио | 11:51:03 |
В Новосибирске | 09:51:03 |
В Петербурге | 05:51:03 |
В Хельсинки | 05:51:03 |
В Стокгольме | 04:51:03 |
В Нью-Йорке | 22:51:03 |
В Лос-Анджелесе | 19:51:03 |
Список часовых поясов PHP
Указывать без пробелов между именами собственными и /