php date timezone set offset
DateTime::setTimezone
(PHP 5 >= 5.2.0, PHP 7, PHP 8)
Описание
Список параметров
Возвращаемые значения
Возвращает объект DateTime для связывания методов.
Примеры
Пример #1 Пример использования DateTime::setTimeZone()
Результат выполнения данных примеров:
Смотрите также
User Contributed Notes 6 notes
In response to the other comments expressing surprise that changing the timezone does not affect the timestamp:
A UNIX timestamp is defined as the number of seconds that have elapsed since 00:00:00 (UTC), Thursday, 1 January 1970.
So: with respect to UTC. Always.
Calling setTimezone() never changes the actual «absolute», underlying, moment-in-time itself. It only changes the timezone you wish to «view» that moment «from». Consider the following:
The timestamp value represented by the DateTime object is not modified when you set the timezone using this method. Only the timezone, and thus the resulting display formatting, is affected.
This can be seen using the following test code:
= new DateTimeZone ( ‘America/Denver’ );
$ESTTZ = new DateTimeZone ( ‘America/New_York’ );
= new DateTimeZone ( ‘America/Denver’ );
$ESTTZ = new DateTimeZone ( ‘America/New_York’ );
It appears that what forzi at mail333 dot com said is correct.
In any case, other output values from format() seem to be accurate, and the true timestamp is always accessible via getTimestamp().
I found unexpected behaviour when passing a timestamp.
timezone seems to always be GMT+0000 unless setTimezone() is set.
= new DateTimeZone ( ‘America/Denver’ );
$ts = 1336476757 ;
/** Output:
string(8) «GMT+0000»
string(10) «1336476757»
string(3) «MDT»
string(10) «1336476757»
**/
Get timezone location from offset
4 Answers 4
You actually can’t reliably do this. Each named time zone has multiple unique properties that change over time. The current offset is only part of the information. You also have to consider how daylight saving time applies, which could apply differently (or not at all) per time zone. You also have to consider how a single time zone can have a history of different values as they may have changed their offsets or DST rules many times over.
You should also consider that at any given time, several different time zones will be using the same offset. If you just pick one at random, you are ignoring a lot of important details!
The other answers here may return a value, but they are all based on false assumptions. A time zone simply can’t be represented by a number alone.
You can search the output of DateTimeZone::listAbbreviations() for timezones which match your offset:
As Matt points out, this function doesn’t take into account the historical changes in DST.
So here’s an improved function which does:
It uses DateTimeZone::getTransitions() to get each timezone’s offset at a particular moment in history.
returns a list of timezones which have an offset of 19800 seconds right now:
returns a list of timezones which had an offset of 19800 seconds on 1st Jan 2000:
Notice that Asia/Colombo has disappeared, because on 1st Jan 2000 its offset was 21600 seconds.
There is, yes. I’ll just quote this excellent answer by uınbɐɥs:
I’d encourage you to take a look at his answer in detail, since there’s a bug that you might need to take into account.
EDITED (original answer completely scrapped)
One approach would be to create a map of offset hour strings (such as +0800 ) to a timezone name that PHP recognizes. It’s not 1-to-1, since there are multiple names for each offset. But since you care about the offset and not the name, then your mapping can just choose any of the available timezone names for any given offset.
Since there aren’t hundreds and hundreds of timezones, you really only end up with an array of about 35 entries (there are a few timezones at the 30-minute or even 45-minute mark).
Here is a code sample that pretty much does what you need:
The for loop just demonstrates the setting of almost all the different timezones based on an iterating offset (I excluded the 30-minute and 45-minute mark timezones, for simplicity).
Here is an excerpt of the output from running the above code:
Credit goes to @Eugene Manuilov for his StackOverflow answer regarding PHP Timezones, as it meant I did not have to write up the array entirely from scratch.
Convert UTC offset to timezone or date
A head scratcher for you.
I am grabbing geo IP data from IPInfoDB’s API and it returns a timezone offset from UTC including DST (if currently reflected).
This is wonderful since DST is a freaking headache. But to my surprise, it caused another headache.
I load this data in PHP to be passed via AJAX to the application. I would like to have the live local time of the IP address on the app.
I have that all set perfectly, but I am going crazy trying to figure out how to set the PHP timezone to match the offset so I can just grab the current hours date(‘H’); and minutes date(‘i’); to pass to via AJAX.
I am unsure if there is a specific function that can just give me the current hours and minutes based on that offset or if there is a practical way to set the timezone based on the offset (which will have DST already applied if is in effect).
I’ve been searching and searching Google to find an answer to this, but what I am doing is more specific since DST is already applied.
The timezone returned from the function is Chile/EasterIsland which I have a feeling is the cause. If I could, I would make this only work for the USA, but I do need it to be worldwide.
This is the function I have now. Please excuse the extremely messy code. I have been playing around with tons of things over the last few hours trying to figure out a solution.
Most of the functionality was found online.
I included the switch/case for certain timezones that are :30 and :45 out there. There may be a way to include that also without the need of the switch/case.
I would appreciate any help or a point in the right direction. I’m not very novice with PHP, but offsets are a new story for me. Thanks!
Класс 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: