0

我正在尝试计算两个日期之间的天数差异。我的行为很奇怪 - 我已将其范围缩小到 2013 年 10 月 6 日和 7 日,如下所示。只要日期范围跨越这些日期,计算就是一天。

// WRONG! current year - 2013
$datediff = strtotime('2013-10-07') - strtotime('2013-10-06');
$startToEndDays = floor($datediff/(60*60*24));
print_r($startToEndDays); // Outputs 0 - should output 1

// RIGHT! next year - 2014
$datediff = strtotime('2014-10-07') - strtotime('2014-10-06');
$startToEndDays = floor($datediff/(60*60*24));
print_r($startToEndDays); // Outputs 1 - correct

知道这里可能是什么问题吗?

4

1 回答 1

2

哈哈好吧,事实证明,2013 年 10 月 6 日/7 日是澳大利亚悉尼开始夏令时的时间。因此,这些日期之间的小时数(正确)计算为 23。但是,23 小时并不是一天。

如果您使用的是 PHP 5.3+,那么您应该以天为单位计算日期之间的差异,以避免任何夏令时问题:

$startDate = new DateTime('2013-10-07');
$endDate = new DateTime('2013-10-06');
$interval = $startDate->diff($endDate);
$days = $interval->days;
于 2013-09-04T04:56:59.520 回答