How do you handle timezone difference calculation in PHP?
I'm being told that this below method of calculating the user's local time is sometimes not working. What's the best way to do this in PHP? What do you do?
public function getTimeOffset ($time) {
$this->_cacheTimeOffset();
if ($this->timeOffsetExecuted) {
$d = date("O");
$neg = 1;
if (substr($d, 0, 1) == "-") {
$neg = -1;
$d = substr($d, 1);
}
$h = substr($d, 0, 2)*3600;
$m = substr($d, 2)*60;
return 开发者_Python百科$time + ($neg * ($h + $m) * -1) + (($this->timeOffset + $this->getDstInUse()) * 3600);
}
return $time;
}
Use the DateTime extension, such as DateTime::getOffset,
or DateTimeZone::getOffset
Some countries might have perform several timezone update,
this method DateTimeZone::getTransitions reveal the transition history
Just answered a very similar question over here. I recommend you check that one out; I explained the two preferred ways of doing timezone offset calculation (using simple math, and then the datetimezone
and datetime
classes) pretty thoroughly.
The first way would be the easiest (and most logical) way, and that is to store their offset (if you already have it, that is) and multiply that by 3600 (1 hour in seconds), and then add that value to the current unix timestamp to get their final time of running.
Another way to do it is to use the
DateTime
andDateTimeZone
classes. How these two classes work, as shown here, is that you create twoDateTimeZone
objects, one with your timezone and one with theirs; create twoDateTime
objects with the first parameters being"now"
and the second being the reference to theDateTimeZone
objects above (respectively); and then call thegetOffset
method on your timezone object passing their timezone object as the first parameter, ultimately getting you the offset in seconds that can be added to the current unix timestamp to get the time that their job needs to run.
date('Z');
returns the UTC offset in seconds.
A quick solution:
<?php echo date('g:i a', strtotime("now + 10 hours 30 minutes")); ?>
精彩评论