- date_default_timezone_set
- Parameters
- Return Values
- Examples
- See Also
- User Contributed Notes
- Настройка Timezone в php.ini
- Настройка Timezone в php.ini
- Добавить комментарий Отменить ответ
- Рубрики
- соц сети
- Архив новостей
- Свежие записи
- Свежие комментарии
- Php date timezone setting php ini
- User Contributed Notes
- How to set timezone with PHP easily (multiple methods)
- Short guide on how to set the timezone using PHP using multiple methods.
- Quick solution
- Set timezone with PHP functions
- Set timezone with PHP using date_default_timezone_set
- Set timezone with PHP using DateTime
- Set timezone with PHP using ini_set
- Set timezone using server-side configuration
- Final thoughts
- You might also like
- References
date_default_timezone_set
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
The timezone identifier, like UTC , Africa/Lagos , Asia/Hong_Kong , or Europe/Lisbon . The list of valid identifiers is available in the List of Supported Timezones.
Return Values
This function returns false if the timezoneId isn’t valid, or true otherwise.
Examples
Example #1 Getting the default timezone
if ( strcmp ( $script_tz , ini_get ( ‘date.timezone’ ))) echo ‘Script timezone differs from ini-set timezone.’ ;
> else echo ‘Script timezone and ini-set timezone match.’ ;
>
?>
See Also
User Contributed Notes
- Date/Time Functions
- checkdate
- date_add
- date_create_from_format
- date_create_immutable_from_format
- date_create_immutable
- date_create
- date_date_set
- date_default_timezone_get
- date_default_timezone_set
- date_diff
- date_format
- date_get_last_errors
- date_interval_create_from_date_string
- date_interval_format
- date_isodate_set
- date_modify
- date_offset_get
- date_parse_from_format
- date_parse
- date_sub
- date_sun_info
- date_sunrise
- date_sunset
- date_time_set
- date_timestamp_get
- date_timestamp_set
- date_timezone_get
- date_timezone_set
- date
- getdate
- gettimeofday
- gmdate
- gmmktime
- gmstrftime
- idate
- localtime
- microtime
- mktime
- strftime
- strptime
- strtotime
- time
- timezone_abbreviations_list
- timezone_identifiers_list
- timezone_location_get
- timezone_name_from_abbr
- timezone_name_get
- timezone_offset_get
- timezone_open
- timezone_transitions_get
- timezone_version_get
Настройка Timezone в php.ini
Настройка часового пояса (по умолчанию) очень необходим для правильной обработки данных. Эта статья «Настройка Timezone в php.ini» поможет вам узнать, как можно настроить часовой пояс в файле конфигурации PHP (php.ini) или внутри любого PHP-скрипта для временного использования.
Настройка Timezone в php.ini
Для установки часового пояса по умолчанию для вашей PHP среды, выполните следующие 4 простых шага.
1. Необходимо найти конфигурационный файл php.ini и это можно сделать:
По умолчанию php.ini лежит в:
Для CentOS,RedHat или Fedora будет лежать:
Для Ubuntu, Debian или LinuxMint будет лежать:
2. Следующим действием будет поиск временных зон ( для вашей локации), для этого, стоит посетить сайт и найти свою зону для php:
3. Прописываем найденную зону в файл php.ini. Для примера, я возьму свою зону — ‘Europe/Kiev’. Открываем конфигурационный файл и делаем изменения:
ВНИМАНИЕ! Поищите опцию «date.timezone» в данном файле, возможно данный параметр уже прописан.
4. Перезапускаем веб-сервер:Если другой сервер (nginx, tomcat, lighttpd), то перезапустите его.
Так же, можно прописать данный параметр в самом php файле следующим образом:
Настройка Timezone в php.ini завершена.
Добавить комментарий Отменить ответ
Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.
Рубрики
- Arch Linux (167)
- Commands (36)
- Debian’s (635)
- Administration tools Ubuntu (37)
- Backups Debian’s (7)
- Database в Ubuntu (58)
- Games (игры) (1)
- Monitoring в Debian и Ubuntu (49)
- Virtualization в Ubuntu / Debian/ Linux Mint (41)
- Docker (22)
- Kubernetes (6)
- KVM (4)
- OpenVZ (3)
- Vagrant (5)
- VirtualBox (6)
- ArgoCD (1)
- Concourse (1)
- Gitlab (1)
- Jenkinks (4)
- Spinnaker (1)
- Apache (32)
- Cherokee (1)
- FTP-services (5)
- Lighttpd (1)
- Nginx (26)
- PHP (27)
- Proxy для Debian’s (2)
- Tomcat (4)
- Панели управления в Ubuntu/Debian/Mint (24)
- Установка и настройка почты на Ubuntu/Debian (12)
- Хранилища (clouds) (2)
- Administration tools freeBSD (19)
- Database во FreeBSD (52)
- Monitoring во freeBSD (37)
- Virtualization во FreeBSD (22)
- VoIP (1)
- Установка Web сервисов (91)
- Установка и настройка почты (6)
- Установка из ports (пакетов) (19)
- Установка из sorce code (исходников) (23)
- Непрерывная интеграция (CI) (27)
- Database в MacOS (36)
- Monitoring в Mac OS (31)
- Security (безопасность) (12)
- Virtualization в Mac OS (30)
- Docker (19)
- Kubernetes (6)
- Vagrant (5)
- VirtualBox (5)
- ArgoCD (1)
- CircleCI (1)
- Concourse (1)
- Gitlab (1)
- Jenkinks (4)
- Spinnaker (1)
- Administration tools CentOS (49)
- Backups RPM’s (4)
- Database в CentOS (68)
- Monitoring в CentOS (67)
- Virtualization в CentOS/ Red Hat/ Fedora (42)
- Docker (23)
- Kubernetes (6)
- KVM (5)
- OpenVZ (2)
- Vagrant (5)
- VirtualBox (6)
- VMWare (3)
- ArgoCD (1)
- Concourse (1)
- Gitlab (1)
- Jenkinks (4)
- Spinnaker (1)
- Apache (35)
- Cherokee (1)
- DNS (3)
- FTP (10)
- Nginx (33)
- PHP (34)
- Proxy для RedHat’s (2)
- Tomcat (2)
- Voice (2)
- Панели управления в CentOS/Red Hat/Fedora (27)
- Прокси сервер на CentOS/RHEL/Fedora (4)
- Установка и настройка почты на CentOS/RHEL/Fedora (14)
- Хранилища (clouds) (1)
соц сети
Архив новостей
Свежие записи
Свежие комментарии
- Глеб к записи Установка Adobe Flash Player в Debian/Ubuntu/Mint
- Максим к записи Заблокировать User Agents используя Nginx
- Денис к записи Как включить EPEL репозиторий на CentOS
- Гость к записи Закомментировать/Раскомментировать строки vi/vim в Unix/Linux
- Sergey к записи Установка и настройка OpenVPN сервера на Debian/Ubuntu/Linux Mint
Php date timezone setting php ini
Поведение этих функций зависит от установок в php.ini .
Настройки конфигурации даты/времени
Имя По умолчанию Место изменения Список изменений date.default_latitude «31.7667» PHP_INI_ALL date.default_longitude «35.2333» PHP_INI_ALL date.sunrise_zenith «90.833333» PHP_INI_ALL До PHP 8.0.0 значение по умолчанию было «90.583333». date.sunset_zenith «90.833333» PHP_INI_ALL До PHP 8.0.0 значение по умолчанию было «90.583333». date.timezone «UTC» PHP_INI_ALL Для подробного описания констант PHP_INI_*, обратитесь к разделу Где могут быть установлены параметры конфигурации.
Краткое разъяснение конфигурационных директив.
Широта по умолчанию. в диапазоне от 0 на экваторе до +90 к северу и -90 к югу.
Долгота по умолчанию. в диапазоне от 0 на нулевом меридиане до +180 на восток и -180 на запад.
Угол, под которым солнце светит во время восхода.
Значение по умолчанию составляет 90°50′. Дополнительные 50′ обусловлены двумя компонентами: радиусом Солнца, который составляет 16′ и атмосферной рефракцией, которая составляет 34′.
Угол, под которым солнце светит во время заката.
Часовой пояс, используемый по умолчанию всеми функциями даты/времени. Порядок приоритета используемых часовых поясов описан на странице date_default_timezone_get() . Смотрите также Список поддерживаемых часовых поясов.
Замечание: Первые четыре опции настройки в настоящее время используются только в функциях date_sunrise() и date_sunset() .
User Contributed Notes
How to set timezone with PHP easily (multiple methods)
Short guide on how to set the timezone using PHP using multiple methods.
Quick solution
The easiest way to set timezone with PHP is by the date_default_timezone_set() function. This function sets the default timezone used by all date/time functions in PHP. For example, to set the timezone to Asia/Hong_Kong :
date_default_timezone_set('Asia/Hong_Kong');
For a full list of supported timezones, check the official PHP.net Documentation timezone list. That is how to set timezone with PHP. For more methods and examples, please check the rest of the article.
Set timezone with PHP functions
Set timezone with PHP using date_default_timezone_set
date_default_timezone_set(string $timezoneId): bool
Where $timezoneId is the string of the timezone to be set. The function will return true if the timezone is valid, else it will return false. Tips: To get the current timezone that is set in PHP configuration, use date_default_timezone_get function:
echo date_default_timezone_get(); // returns the configured timezone
Set timezone with PHP using DateTime
Another method to set timezone with PHP is by object-oriented way using the DateTime object and the DateTimeZone class. The major difference here is the timezone will be set only per created object. Therefore, this method can be used when you want to have multiple variables with multiple timezones, or if the timezone is interchangeable. For example, we want to have two DateTime object with different timezones:
$dateHongKong = new DateTime('2023-01-01', new DateTimeZone('Asia/Hong_Kong')); echo $dateHongKong->format('Y-m-d H:i:sP'); // 2023-01-01 00:00:00+08:00 $dateJapan = new DateTime('2023-01-01', new DateTimeZone('Asia/Tokyo')); echo $dateJapan->format('Y-m-d H:i:sP'); // 2023-01-01 00:00:00+09:00
Another example is a single DateTime object that can have its timezone updated with DateTime::setTimezone() :
// Hong Kong timezone $date = new DateTime('2023-01-01', new DateTimeZone('Asia/Hong_Kong')); // Change to Japan timezone $date->setTimeZone(new DateTimeZone('Asia/Tokyo'));
Set timezone with PHP using ini_set
We can also modify timezone configuration dynamically using ini_set function to modify the date.timezone configuration variable:
ini_set('date.timezone', 'America/New_York');
Set timezone using server-side configuration
- In php.ini file, look for the [Date] section;
- Uncomment the date.timezone configuration line by removing the ; sign at the beginning of the line;
- Input the desired timezone after the = sign.
. [Date] ; Defines the default timezone used by the date functions ; http://php.net/date.timezone date.timezone = Asia/Japan .
Remember to restart the web server after changing the setting in php.ini .
Final thoughts
These are the methods to set timezone with PHP using multiple methods. We hope these methods are helpful to you, and that they can be utilized in many use cases.
You might also like
References