date_default_timezone question
I wrote a pretty long function that will calculate the differences in timezones across the U.S. relative to the server timezone. I have noticed that by using default_t开发者_StackOverflow社区imezone_set() that I can get the same data back that my function calculates. I have chosen not to use the default_timezone_set function because I am afraid that this changes the time on a global level and that if another request somewhere else is occurring within my app, that the wrong time will be used; that is, the time that is being calculated at that moment using the default_timezone_set function.
Can someone verify this for me? Can I just use the timezone_set function without having to worry about the possibility of incorrect times being used in other functions? Hope this is clear.
You should take a look at how PHP determines what timezone to use in the absence of date_default_timezone_set()
. It's described under the date_default_timezone_get() function.
Basically, if you're not using date_default_timezone_set()
, then PHP is most likely using the server timezone as the default timezone for all the date functions anyway, unless you happened to have set one of the other settings listed under date_default_timezone_get()
.
If you specifically set the timezone using date_default_timezone_set()
, then you are making sure of the timezone that your code will use, rather than letting the server timezone decide for you.
If you want to use the server timezone, then it's good practice to simply set the timezone to the server timezone using date_default_timezone_set()
, and all ambiguity is removed.
So, it's too late for the short answer, but the short answer is yes, you should be able to use date_default_timezone_set()
safely.
PHP already has a function to calculate the offsets between timezones:
timezone_offset_get()
Under the PHP manual, sample use case is shown. timezone_offset_get(). Here is an example of how to calculate the time offset between two timezones.
$offset = get_timezone_offset('America/Los_Angeles','America/New_York'); //result is 10800 (3 hours)
$offset = get_timezone_offset('America/Los_Angeles'); //compares against default server timezone
After getting the offset in seconds, you can do whatever calculations you need to do.
Regarding setting the default timezones there are two ways to go about doing it.
Adjust php.ini to set the default timezone (add the following line in the php.ini file)
date.timezone = "Your/Timezone"
Adjust the default timezone at runtime (using the mentioned
date_default_timezone_set("Your/Timezone")
)
Depending on the server setup. Chaning the php.ini may not take effect due to php.ini precedence. There may be other php.ini somewhere in the server that takes precedence than the one you are editing
精彩评论