get UTC time in PHP
How can I get UTC/GMT +/- time stamp using PHP’s date() function? For example, if I try
I will get Unix time stamp; but I need to get UTC/GMT time stamp with string GMT/UTC+/-0400 or GMT/UTC+/-1000 based on local timings.
12 Answers 12
A simple gmdate() will suffice
The DateTime __construct() documentation suggests passing «now» as the first parameter when creating a DateTime instance and specifying a timezone to get the current time.
Obtaining UTC date
Obtaining UTC timestamp
The result will not be different even you have date_default_timezone_set on your code.
Other than calling gmdate you can also put this code before your rest of the code:
That will make rest of your date/time related calls to use GMT/UTC timezone.
You can use gmmktime function without arguments to obtain the current UTC timestamp:
gmmktime will only work if your server time is using UTC. For example, my server is set to US/Pacific. the listed function above echos back Pacific time.
with string GMT/UTC +/-0400 or GMT/UTC +/-1000 based on local timings
Your custom format is just missing O to give you the timezone offsets from local time.
Difference to Greenwich time (GMT) in hours Example: +0200
However, for maximized portability/interoperability, I would recommend using the ISO8601 date format c
You can use also gmdate and the timezone offset string will always be +00:00
Время в PHP, смещение от GMT, UTC
Для начала разберемся что такое GMT и UTC. Во многих источниках они упоминаются как синонимы, и между ними действительно не существенная разница (до 1 секунды).
Их отличие в методике получения точного значения. UTC (универсальное координированное время) измеряется благодаря высокоточным атомным часам. GMT (Время гринвичского или нулевого меридиана) получают благодаря астрономическим расчетам. При этом UTC периодически подгоняют, чтобы расхождение с GMT составляло не более секунды.
Для бытовых целей это расхождение не важно и потому UTC и GMT можно использовать как одно и тоже число.
Время, используемое в PHP
Речь идет о функции time(). Она возвращает так называемый UNIX_TIMESTAMP, время в секундах с 1 Января 1970 года.
Какое время возвращает PHP «по умолчанию»? Для какого часового пояса? Установка по умолчанию часового пояса выполняется в файле php.ini. Например, здесь установлен часовой пояс Лос Анджелеса:
Но если настройки не менялись после установки PHP, то обычно вы там обнаружите UTC, что соответствует часовому поясу GMT:
В программе, вы можете установить нужный вам часовой пояс.
Это можно сделать вот так:
Если используется второй способ, то он устанавливает приоритетное значение часового пояса для функций времени в PHP.
Функция time(), показывает время именно для того часового пояса, который установлен в текущий момент в настройках или date_default_timezone_set().
Как узнать разницу времени между локальным часовым поясом и GMT?
Мы разобрались, что time() показывает время для выбранного часового пояса. Разницу времени локального времени (LT) от GMT и текущий код часового пояса можно получить с помощью ключей функции date(). Рассмотрим следующий пример.
Z — разницу в секундах, при этом пояса западнее GMT дают отрицательные значения, а восточнее — положительные;
e — идентификатор часового пояса (появился в PHP 5.1);
P — разница с GMT в часах и минутах (появился в PHP 5.1.3),
T — аббревиатура часового пояса.
Есть и другие ключи, все они перечислены в документации функции date().
Кстати, через 22 года (19 января 2038) для хранения времени в таком формате уже не будет хватать 32 битного целого числа со знаком. Вполне возможно, что 32 битных приложений уже к тому времени не останется, так что проблемы переполнения не возникнет. 64х-битной переменной уже должно хватить на 292 млрд. лет. Можно уже сейчас проектировать базы данных с учетом этого факта.
Данная запись опубликована в 14.01.2016 19:51 и размещена в PHP. Вы можете перейти в конец страницы и оставить ваш комментарий.
Валидатор для JSON строки в PHP
Удаление элементов из массива в PHP
Класс DateTimeZone
(PHP 5 >= 5.2.0, PHP 7, PHP 8)
Введение
Представление часового пояса.
Обзор классов
Предопределённые константы
Часовые пояса Африки.
DateTimeZone::AMERICA
Часовые пояса Америки.
DateTimeZone::ANTARCTICA
Часовые пояса Антарктики.
DateTimeZone::ARCTIC
Часовые пояса Арктики.
DateTimeZone::ASIA
Часовые пояса Азии.
DateTimeZone::ATLANTIC
Часовые пояса Атлантики.
DateTimeZone::AUSTRALIA
Часовые пояса Австралии.
DateTimeZone::EUROPE
Часовые пояса Европы.
DateTimeZone::INDIAN
Часовые пояса Индии.
DateTimeZone::PACIFIC
Часовые пояса Тихого океана.
DateTimeZone::UTC
DateTimeZone::ALL
DateTimeZone::ALL_WITH_BC
Все часовые пояса, включая обратно совместимые.
DateTimeZone::PER_COUNTRY
Число часовых поясов на страну.
Содержание
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.
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 convert datetime to UTC
I am in need of an easy way to convert a date time stamp to UTC (from whatever timezone the server is in) HOPEFULLY without using any libraries.
16 Answers 16
Use strtotime to generate a timestamp from the given string (interpreted as local time) and use gmdate to get it as a formatted UTC date back.
Example
As requested, here’s a simple example:
(But this does use a Class)
Without any classes you could try something like this:
NOTE: You might need to set the timezone back to the original as well
Check the reference:
If you have a date in this format YYYY-MM-HH dd:mm:ss, you can actually trick php by adding a UTC at the end of your «datetime string» and use strtotime to convert it.
This will print this:
And as you can see it takes care of the daylight savings time problem as well.
A little strange way to solve it. 🙂
Convert local time zone string to UTC string.
e.g. New Zealand Time Zone
If you don’t mind using PHP’s DateTime class, which has been available since PHP 5.2.0, then there are several scenarios that might fit your situation:
If the given datetime string is in some timezone different from the one in your PHP configuration, then create the datetime object by supplying the correct timezone (see the list of timezones PHP supports). In this example we assume the local timezone in Amsterdam:


