время по гринвичу php
Как вывести время с учётом часового пояса в PHP
Иногда требуется сделать такой сайт, на котором время будет подстраиваться под часовой пояс пользователя. Задача эта непростая в том плане, что определить часовой пояс пользователя проблемно. Поэтому выводят в 99% случаев время, соответствующее серверному часовому поясу. Но давайте с Вами разберём, как всё-таки можно вывести время с учётом временной зоны конкретного пользователя.
Как я уже написал, определить часовой пояс пользователя сложно, об этом мы поговорим в следующей статье. А пока что будем считать, что мы уже знаем временное смещение относительно серверного времени.
Лучше всего будет поставить серверное время по Гринвичу. И сохранять надо все данные со временем именно по Гринвичу. Я уже когда-то писал, что хранить надо в той же базе данных не строковый формат даты и времени, а числовой, то есть тот, который возвращается функцией time().
Давайте с Вами разберём небольшой код:
Примерно так и работает вывод времени с учётом часового пояса пользователя на PHP. Безусловно, можно и не ставить по умолчанию время по Гринвичу, а узнавать смещение относительно серверного времени. Впрочем, о смещении мы с Вами поговорим в следующей статье.
Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Порекомендуйте эту статью друзьям:
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
Комментарии ( 5 ):
если таким скриптом,то да.можно функцию смены написать по дате
а можно немного поподробнее? 🙂 можно эту ф-ию в студию? а то я уже больше месяца не могу до конца разобраться с этими ф-иями даты и времени.
Для добавления комментариев надо войти в систему.
Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.
Copyright © 2010-2021 Русаков Михаил Юрьевич. Все права защищены.
gmstrftime
(PHP 4, PHP 5, PHP 7, PHP 8)
gmstrftime — Форматирует дату/время по Гринвичу с учётом текущей локали
Описание
Список параметров
Возвращаемые значения
Список изменений
Версия | Описание |
---|---|
8.0.0 | timestamp теперь допускает значение null. |
Примеры
Пример #1 Пример использования функции gmstrftime()
Смотрите также
User Contributed Notes 4 notes
HTTP 1.1 (RFC 2068) requires an RFC 1123 date with a four digit year, so the correct format to use for a Last-modified header would look something like this:
If you want the dutch time on your pages and you are hosted on a server in the USA you can easily change it this way:
I needed it for a dutch guestbook.
I’m new to PHP and it took me a while to find it out and maybe it’s of no use for experienced PHP programmers but I thought people can always ignore my post 🙂
To get a RFC 850 date (used in HTTP) of the current time:
gmstrftime («%A %d-%b-%y %T %Z», time ());
This will get for example:
Friday 25-Jun-04 03:30:23 GMT
Please note that times in HTTP-headers _must_ be GMT, so use gmstrftime() instead of strftime().
gmstrftime() should not be used to generate a RFC 850 date for use in HTTP headers, since its output is affected by setlocale().
How do I get Greenwich Mean Time in PHP?
I have a server which is set to EST, and all records in the database are set to EST. I would like to know how to set it to GMT. I want to offer a time zone option to my users.
6 Answers 6
I would strongly suggest avoiding messing with UNIX timestamps to make it look like a different time zone. This is a lesson I’ve learnt the hard way, way too many times.
A timestamp is the number of seconds since Midnight 1 January 1970, GMT. It doesn’t matter where you are in the world, a given timestamp represents the exact same moment in time, regardless of time zones. Yes, the timestamp «0» means 10am 1/1/70 in Australia, Midnight 1/1/70 in London and 5pm 31/12/69 in LA, but this doesn’t mean you can simply add or subtract values and guarantee accuracy.
The golden example which stuffed me up every year for way too long was when daylight savings would crop up. Daylight savings means that there are «clock times» which don’t exist in certain parts of the world. For example, in most parts of the US, there was no such time as 2:01am on April 2, 2006.
Enough quasi-intelligible ranting though. My advice is to store your dates in the database as timestamps, and then.
This will keep your values clean (you don’t have to be worrying about adding offsets, and then subtracting before saving), it will respect all Daylight Savings rules, and you also don’t have to even look up the timezone of the place you want.
gmmktime
(PHP 4, PHP 5, PHP 7, PHP 8)
gmmktime — Возвращает локальную метку времени Unix для времени по Гринвичу
Описание
Список параметров
Возвращаемые значения
Возвращает временную метку Unix ( int ) в случае успешного выполнения или false в случае возникновения ошибки..
Список изменений
Примеры
Пример #1 Базовый пример использования gmmktime()
Смотрите также
User Contributed Notes 19 notes
The interaction of timezones with unix timestamps is a bit tricky so I thought I’d clarify so that people aren’t led too far astray by Greg’s and Glen’s comments. 🙂
In the POSIX standard, «unix time» does not have a specified timezone. It is universal. For most intents and purposes you can think of them as always being GMT/UTC. (And you can derive the UTC time from a «timestamp» by dividing it by 86400 and looking at the modulus.) Do not ever try to adjust a timestamp by a timezone offset (specifically, do not ever use the code at the end of Glen’s note). Timezones are basically used only when «rendering» a timestamp from «unix time» into a «civil time» date/time string.
Let’s take an example. PST is GMT-8, and EST is GMT-5. So when it is 3 AM in PST, it is 6 AM in EST. At that exact moment in time, the _timestamp_ is identical in both time zones. If I am sitting at my computer in PST, and you are at yours in EST, and I call you up and read you the current unix timestamp on my computer, it will match yours (assuming our clocks are both set accurately for our timezone).
So, time() always will return the same thing at the same actual moment, anywhere in the world. gmmktime() and mktime(), when given specific time parameters, convert those time parameters FROM the appropriate timezone (GMT for gmmktime(), local time for mktime()), before computing the appropriate timestamp. Again, for most intents and purposes you can imagine that mktime() first converts your input parameters to GMT and then calls gmmktime() which produces a GMT timestamp. (For the purposes of this explanation, please ignore the fact that the PHP documentation says that internally gmmktime() calls mktime().)
HOWEVER, when called with no arguments, gmmktime() uses the current GMT time, and mktime() uses the current local time. So, if you imagine the above conversion taking place where mktime() converts the (current) local time to GMT, it ends up essentially calling gmmktime() with the _current_ GMT time, just like gmmktime() does all by itself.
This is why time(), gmmktime(), and mktime() all return the same exact timestamp, _when called with no arguments_. This is why Glen saw them all produce the same thing.
Greg wrote that gmmktime() will return something different if you are not sitting in the GMT timezone, but this is only true if you have given it arguments from which to construct a timestamp.
So let’s look at that situation again. Say I am in PST and it’s 3 AM PST. (And therefore it is 11 AM GMT.) mktime() lets me override one field at at time, and the first argument is, conveniently, the hour field. So if I call mktime(3), I get the same answer as mktime(). Makes sense, right? I just told it to give me the timestamp corresponding to 3 AM local time. If I call gmmktime(11), I get the same answer as gmmktime(), since it is currently 11 AM GMT. mktime(3) and gmmktime(11) refer to the same exact point in time, because PST is 8 hours behind GMT. So it makes sense that mktime(3) == gmmktime(11). And sine mktime() == mktime(3) (at this moment), and gmmktime() == gmmktime(11) (at this moment), it makes sense that gmmktime() == mktime().
Okay, that should be all you need to know to deal with the interaction between timestamps and timezones. Don’t ever try to convert timezones by adding or subtracting to the timestamp. Timestamps don’t really have timezones, it is apples and oranges, and you’ll either get the wrong answer in some situations or end up with code that no one can maintain. Leave it up to the higher-level PHP functions to do the conversion. (If you want to hack things, strtotime is handy and it can work with timezones; let it do the hard work for you.)
I had a problem with hosting a UK site on a US server, the times didnt match (obviously) and also didnt account for daylight savings time. The daylight savings dates and times of change differ worldwide, so detecting if the server was in dst wouldnt work (see http://webexhibits.org/daylightsaving/).
Here is a function for creating a timestamp which can be used by date() to create all the parameters required to display the local time (site not server). I have used GMT time to create the timestamp as there is no offset for UK time (+00).
In addition to GLEN’s post on DEC 5th 2007
(Just a note for others)
The results for the three time types Glen listed under «returns» all returned the exact same timestamp
— 1196812966
Using those three functions will only make the exact same timestamp if the server the code is executed on IS in GMT timezone.
‘mktime()’ and ‘time()’ will both return the timestamp for your server time, and will both be the same as eachother.
gmmktime will return a GMT timestamp.
So if run on a server that is NOT in the GMT timezone then gmmktime will return a different timestamp to the other two.
$secondsInDay = 60 * 60 * 24 ;
gmdate
(PHP 4, PHP 5, PHP 7, PHP 8)
gmdate — Форматирует дату/время по Гринвичу
Описание
Эта функция идентична функции date() за исключением того, что возвращает время по Гринвичу (GMT).
Список параметров
Возвращаемые значения
Возвращает строку с форматированной датой.
Список изменений
Версия | Описание |
---|---|
8.0.0 | timestamp теперь допускает значение null. |
Примеры
Пример #1 Пример использования gmdate()
Смотрите также
User Contributed Notes 17 notes
If you have the same application running in different countries, you may have some troubles getting the local time..
In my case, I was having troubles with a clock created with Macromedia Flash. the time shown by the clock was supposed to be set up by the server, passing the timestamp. When I moved the file to another country, I got a wrong time.
You can use the timezone offset ( date(«Z») ) to handle this kind of thing.
Wath out for summer time and winter time.
If you want to get the current date and time based on GMT you could use this :
Note that date(«I») returns 1 in summer and 0 in winter.
For an RFC 1123 (HTTP header date) date, try:
Do not use the «T» timezone specifier to generate «GMT», as this may return «UTC» or «GMT+0000» or «Z» or something else which depends on the running platform, which would not be RFC1123 compliant.
Use ‘D, d M Y H:i:s \G\M\T’ which forces the value of the timezone indicator.
Note that RFC1123 requires the use of ENGLISH day and month abbreviations. They MUST NOT be localized!
An example of the RFC1123 format for full dates is:
Sun, 06 Nov 1994 08:49:37 GMT
Note the presence of the leading 0 (RFC1123 dates have a fixed size, and space padding is prohibited because it causes problems with fixed size handling when such dates are used in HTTP headers that may compress whitespaces.
Some proxies accept also the ISO 8601 format, but this is not documented in HTTP/1.1 specs (RFC2616).
Want to put different International Times in your web?
First create a database including the GMT and the DST (find it f.i. at timeanddate.com). Be careful, because there are several different DST dates and options.
Once you have your function which calculates the GMT hour difference (it can be a decimal!!), sum it to the Unix Time (remember that unix time is GMT, not local: f.i. gmdate(«U»)===date(«U)).
Don’t forget to recalculate the GMT difference to seconds before it.
Then format your date using gmdate() (not date()!) and. you’ve got your International Time!
[ «Name» ] = «Barcelona» ;
$city [ «GMT» ] = 1.0 ;
$city [ «actualDST» ] = 1.0 ; //Because it’s summer time
A function to get the ISO 8601 timestamp in UTC with precision up to microseconds
function iso_8601_utc_time($precision = 0)
<
$time = gettimeofday();
Gives user the ability to use their timezone preferences.
I had to create this script for a very large community. I first made any posts to the database that would display the date using just time();
Example: mysql_query(«INSERT INTO `table` (`datetime`) VALUES (‘».time().»‘)»);
This information would be saved in the users table.
To display the date and time in their respective timezone preference:
I also used cookies to store their timezone:
$sth=mysql_query(«SELECT `datetime` FROM `table` LIMIT 1»);
$row=mysql_fetch_assoc($sth);
echo datetime($row[‘datetime’],$_COOKIE[‘timezone’]);
If you want to calculate the time period between two clocked events that happen less than 24 hours apart, for example the daylight period between sunrise and sunset, you can take advantage of the fact that the gmdate() function also accepts a negative timestamp. If you want to present the time period in the format hours:minutes you can use
= ‘7:45’ ; // hours with or without leading zeros
$sunset_clocked = ’21:05′ ; // hours with or without leading zeros
Daylight period is 13:20 (hours:minutes)
The fun part comes in when the sunset time is next day (and therefore in value lower than the sunrise clock time), for example:
$sunrise_clocked = ’18:45′;
$sunset_clocked = ’09:30′;
Daylight period is 14:45 (hours:minutes)
This trick does NOT work with date(), because the output may then be off a number of hours, depending on your time zone.
Tested with PHP 5.6.35 and 7.2.4.