日期计算未按预期运行


Date Calculations Not Behaving As Expected

我有一个PHP函数,可以查找数组中的第一个和最后一个日期,以便它们可以以"5 Feb to 4 Mar"的形式呈现。

但是,我发现有时序列被破坏了,所以我得到的不是"9 月 1 日至 11 月 2 日",而是"9 月 1 日至 10 月 26 日,10 月 27 日至 11 月 2 日"。

代码为:

function daterange($datearray){
if(is_array($datearray)){
$resultArray = array();
$index = -1;
$last = 0;
$textdates = NULL;
foreach ($datearray as $date) {
    $timestamp = strtotime($date);
    if (false !== $timestamp) {
        $diff = $timestamp - $last;
        if ($diff > 86400) {
            $index = $index + 1;
            $resultArray[$index][] = $date;
        } elseif ($diff > 0) {
            $resultArray[$index][] = $date;
        } else {
            // Error! dates are not in order from small to large
        }
        $last = $timestamp;
    }
}

一种给定您发布的内容的方法:

$dates = array_map('strototime', $datearray);
$start = min($dates);
$end   = max($dates);

或者,如果您想要原始数组中的日期:

$dates = array_map('strototime', $datearray);
$start = $datearray[array_search(min($dates), $dates)];
$end   = $datearray[array_search(max($dates), $dates)];

阅读您的评论后,这就是我想出的。 它也许可以简化得更多,但这里是:

$datearray = array( '2014-01-10', '2014-01-11', '2014-02-10', '2014-02-11' );
$dates = array_map('strtotime', $datearray);
sort($dates);
$dates = array_chunk($dates, 2);
foreach($dates as $date) {
    echo $start = date('d M', reset($date));
    echo $end = date('d M', end($date));
}

找到问题和解决方案的关键是导致问题的特定日期。这是我们从英国夏令时更改为格林威治标准时间的那一天,所以一天中实际上有 90000 秒,而不是 86400。

通过改变行

if ($diff > 86400) {

if ($diff > 90000) {

问题解决了!

在其他应用中,春季可能会出现类似的问题,因为一天中一天只有 82800 秒。

我希望这可能会帮助某人,作为对其他人在这里给予我的所有帮助的小额回报。