1

我知道已经有很多问题和答案,但不幸的是我认为我的情况可能是独一无二的?出于某种原因,时间变化似乎使一天计算为比它应该计算的少一天。

这是我正在使用的 PHP,它工作得很好,直到它开始分别与夏令时之前和夏令时之后的开始日期和结束日期重叠(仅供参考,这是一个最近的问题,因为夏令时开始了这周末!):

//$lastDate and $firstDate are 2 unix timestamps with valid month, day, and year values.
//The times are irrelevant at this point, they are only meant to represent a day.

//I start by making sure these have the same time values.
$lastDate = mktime(23, 59, 59, date("m", $lastDate), date("j", $lastDate), date("Y", $lastDate));
$firstDate = mktime(23, 59, 59, date("m", $firstDate), date("j", $firstDate), date("Y", $firstDate));

//Then calculate the total number of days in between.
$totalDays = abs(floor(($firstDate - $lastDate)/(60*60*24)));

因此,再次明确地说,如果我不重叠夏令时更改,则上述工作...

以供参考:

如何找到两个指定日期之间的日期?

PHP中两个unix时间戳之间的实际天数

在php中查找2个unix时间戳之间的天数

而且,我现在还在使用 PHP 5.2。

编辑/更新:
我在这个链接上找到了以下内容:

如何找到两个指定日期之间的日期?

如何计算php中2个unix时间戳之间的间隔而不除以86400(60 * 60 * 24)

//$lastDate and $firstDate are 2 unix timestamps with valid month, day, and year values.
//The times are irrelevant at this point, they are only meant to represent a day.

//I start by making sure these have the same time values.
$lastDate = mktime(10, 00, 00, date("m", $lastDate), date("j", $lastDate), date("Y", $lastDate));
$firstDate = mktime(10, 00, 00, date("m", $firstDate), date("j", $firstDate), date("Y", $firstDate));

//Then calculate the total number of days in between. 
$totalDays = floor($firstDate / 86400) - floor($lastDate/ 86400);

它现在似乎适用于 DST 的交叉。有人看到这有什么问题吗?

4

1 回答 1

2

你在 PHP 5.3+ 上运行吗?ADateInterval非常适合这个问题。
http://www.php.net/manual/en/datetime.diff.php

<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
于 2013-03-08T20:14:41.860 回答