获取最近的日期

时间:2017-02-27 12:37:37

标签: php

我想从一系列日期中获得未来的第一次约会。我试着编写自己的函数,但没有完成任务。

private static function getClosestDate($date, array $dates, $last) {
    $interval               = array();
    $now                    = strtotime(date('Y-m-d'));

    foreach ($dates as $d) {
        $dateTime           = strtotime($date);
        $toTime             = strtotime($d);

        // Do not parse dates older than today
        if (strtotime($d) < $now) { continue 1; }

        // Only do dates in the future
        if ($toTime < $dateTime) { continue 1; }
        $interval[]         = abs($dateTime - $toTime);
    }

    // If there is no interval, use the latest date
    if (!count($interval)) {
        return $last;
    }

    asort($interval);
    $closest                = key($interval);
    return $dates[$closest];
}

此代码有效,但它也可以反过来使用。接下来,当没有上次日期时,它应该使用$ last参数,这是最后一个日期。

我想知道这个的原因是因为我有一系列日期可供人们预订夜晚。我想知道计算他们可以预订的夜晚的天数差异。计算日期差异很容易,但我确实需要知道下次预订何时出现。这些在$ dates参数中提供。

我应该在代码中更改哪些内容以便修复它(我根据$ date参数尝试在过去的日期继续使用foreach)或者有人可以为我提供代码吗?

1 个答案:

答案 0 :(得分:0)

我自己解决了这个问题。而不是使用日期数组我现在使用日期作为间隔中的键来再次检索日期。这确实有效。

private static function getClosestDate($date, array $dates, $last) {
    $interval               = array();
    $now                    = strtotime(date('Y-m-d'));

    foreach ($dates as $d) {
        $dateTime           = strtotime($date);
        $toTime             = strtotime($d);

        // Do not parse dates older than today
        if (strtotime($d) < $now) { continue 1; }

        // Only do dates in the future
        if ($toTime < $dateTime) { continue 1; }
        $interval[$d]       = abs($dateTime - $toTime);
    }

    // If there is no interval, use the latest date
    if (!count($interval)) {
        return $last;
    }

    asort($interval);
    $closest                = key($interval);

    return $closest;
}
相关问题