我需要弄清楚两个时区之间的小时差异,当前方的时区移到第二天时,我遇到了一些问题。
示例:
//Let's say it is 11pm 23:00 in LA
$local_tz = new DateTimeZone('America/Los_Angeles');
$local = new DateTime('now', $local_tz);
$local_hour = $local->format('H');
//NY is 3 hours ahead, so it is 2am, 02:00
$user_tz = new DateTimeZone('America/New_York');
$user = new DateTime('now', $user_tz);
$user_hour = $user->format('H');
按照此问题(Calculate hours between dates in different time zones)中的示例,我得到了错误的结果:
$diff = $user_tz->getOffset($local);
error_log('$diff '.gmdate("H:i:s", $diff)); //outputs 20:00:00
如果是在洛杉矶的下午4点,那么在纽约时间晚上7点那么很容易:
$time_diff = ($user_h - $local_h); //$time_diff = 3;
但是当纽约搬到第二天时,我又得到了不正确的结果:
$time_diff = ($user_h - $local_h); //$time_diff = -21;
那么我怎样才能解释另一个时区已经搬到了新的一天呢?
答案 0 :(得分:3)
您可以使用时区偏移量尝试以下代码获取两个时区之间的小时差:
$local_tz = new DateTimeZone('America/Los_Angeles');
$local = new DateTime('now', $local_tz);
//NY is 3 hours ahead, so it is 2am, 02:00
$user_tz = new DateTimeZone('America/New_York');
$user = new DateTime('now', $user_tz);
$local_offset = $local->getOffset() / 3600;
$user_offset = $user->getOffset() / 3600;
$diff = $user_offset - $local_offset;
print_r($diff); //outputs 3
答案 1 :(得分:0)
我设法找到了一个解决方案,DateInterval类一直为我抛弃21,虽然当我输出对象时我可以看到小时为3.
由于DateTime与epoch进行比较并忽略时区,因此我必须为两个时间创建一个新的DateTime,然后运行比较。
//Let's say it is 11pm 23:00 in LA
$local_tz = new DateTimeZone('America/Los_Angeles');
$local = new DateTime('now', $local_tz);
//NY is 3 hours ahead, so it is 2am, 02:00
$user_tz = new DateTimeZone('America/New_York');
$user = new DateTime('now', $user_tz);
$usersTime = new DateTime($user->format('Y-m-d H:i:s'));
$localsTime = new DateTime($local->format('Y-m-d H:i:s'));
$interval = $usersTime->diff($localsTime);
print_r($interval->h); //outputs 3
使用$user->modify("-4 hours"); $local->modify("-4 hours");
运行测试会返回3.(将其中一个放在前一天的午夜之前)
答案 2 :(得分:-1)
用于计算两个时区之间的小时差的函数(输入应为“ +00:00”格式)。
function timezoneDifferenceInHours( $timezone_1, $timezone_2){
//get hour value of first timezone
$a = explode(":",$timezone_1)[0];
//get hour value of second timezone
$b = explode(":",$timezone_2)[0];
//calculate difference
$difference =0;
if($a < $b)
$difference = $b-$a;
else
$difference = $a-$b;
return $diffsec;
}
函数调用:(返回时区之间的时差,以小时为单位)
echo timezoneDifferenceInHours( "-07:00", "+05:30" );
//Output : 12