为什么它说5,为什么这在技术上是正确的
在Sydney,DST开始于2013-10-06 02:00:00 – 所以你跨越那个日期会失去一个小时.
当你调用strtime时,它会将时间解释为悉尼时间,但返回一个Unix时间戳.如果您将第二组时间戳转换为UTC,则会得到2013-09-30 14:00:00到2013-10-06 13:00:00的范围,这不是6天,所以得到向下舍入到5.
如何获得忽略DST转换的时差
请尝试使用DateTime对象,例如
$tz=new DateTimeZone('Australia/Sydney');
$start=new DateTime('2013-10-01', $tz);
$end=new DateTime('2013-10-07', $tz);
$diff=$end->diff($start);
//displays 6
echo "difference in days is ".$diff->d."\n";
为什么DateTime :: diff的工作方式不同?
你可能会问“为什么会这样?” – 毕竟,在这些时间之间确实没有6天,它是5天23小时.
原因是DateTime::diff实际上纠正了DST转换.我不得不阅读源代码来解决这个问题 – 修正发生在内部timelib_diff函数中.如果满足以下所有条件,则会发生此更正
>每个DateTime使用相同的时区
>时区必须是地理ID,而不是GMT这样的缩写
>每个DateTime必须具有不同的DST偏移(即一个在DST中,一个不在DST中)
为了说明这一点,如果我们在切换到夏令时的任何一侧使用两次几个小时就会发生这种情况
$tz=new DateTimeZone('Australia/Sydney');
$start=new DateTime('2013-10-06 00:00:00', $tz);
$end=new DateTime('2013-10-06 04:00:00', $tz);
//diff will correct for the DST transition
$diffApparent=$end->diff($start);
//but timestamps represent the reality
$diffActual=($end->getTimestamp() - $start->getTimestamp()) / 3600;
echo "Apparent difference is {$diffApparent->h} hours\n";
echo "Actual difference is {$diffActual} hours\n";
这输出
Apparent difference is 4 hours
Actual difference is 3 hours