1

我的 PHP 代码中的 strtotime 有这个问题,有时它是错误的(仅适用于某些时区),而对其他人来说是正确的!

我无法理解它。

我也在<?php date_default_timezone_set('GMT'); ?>页面顶部设置了,但这没有帮助!

基本上它的作用是根据 if 和 else if 条件将offset/3600值添加或减去设置时间。$time1 = strtotime('00:00');

offset/3660 值是两个时区之间的时间差!

下面的代码适用于某些位置,但不适用于其他位置!基本上它会增加额外的 1-2 小时或起飞/减去额外的 1-2 小时(不是所有时间)。

即阿比让和伦敦之间的时差是-1。应显示的时间(值)为 23:00,即 00:00 - 01:00 = 23:00。但显示的值为 00:00。

但是,正如我提到的,它适用于某些时区。即纽约和伦敦之间的时差是-5,代码有效,它显示 19:00 为 00:00 - 05:00 = 19:00

有人可以解释一下吗?

这是有问题的代码:

<?php
$time1 = strtotime('00:00');

if (0 > $offset)
{
   // For negative offset (hours behind)
  $hour_dif = date('H:i', strtotime($time1 -$offset/3600));
  $time1 = "{$hour_dif}";
}
elseif (0 < $offset)
{
   // For positive offset (hours ahead)
     $hour_dif = date('H:i', strtotime($time1 +$offset/3600));
     $time1 = "{$hour_dif}";

}
else
{
   // For offsets in the same timezone.
   $time1 = "in the same timezone";
}

echo "{$time1}";
?>
4

1 回答 1

3

好吧,既然strtotime()已经返回了一个时间戳并date()期望你可以这样做

$hour_dif = date('H:i', ($time1 - ($offset*3600)));

或者

$hour_dif = date('H:i', ($time1 + ($offset*3600)));

分别从时间戳中删除或添加正确的秒数。

我还假设这$offset是以小时为单位的偏移量,因此您必须乘以3600得到秒数,而不是除以。


好吧,在测试你的代码并仔细考虑之后,它变得很明显。

-1您要计算的负偏移量$time1 - (-1) * 3600,我们都知道双重否定是正的...

所以实际上,您的代码可以压缩为:

$time1 = strtotime('00:00');

if ($offset == 0)
     $time1 = "in the same timezone";
else
{
   // For positive offset (hours ahead)
     $hour_dif = date('H:i', ($time1 + ($offset*3600)));
     $time1 = "{$hour_dif}";
}

echo "{$time1}\n";

并且应该按预期工作:

cobra@box ~ $ for i in {-24..24}; do php test.php $i; done;
00:00
01:00
02:00
03:00
04:00
05:00
06:00
07:00
08:00
09:00
10:00
11:00
12:00
13:00
14:00
15:00
16:00
17:00
18:00
19:00
20:00
21:00
22:00
23:00
in the same timezone
01:00
02:00
03:00
04:00
05:00
06:00
07:00
08:00
09:00
10:00
11:00
12:00
13:00
14:00
15:00
16:00
17:00
18:00
19:00
20:00
21:00
22:00
23:00
00:00
于 2013-08-28T14:04:51.973 回答