1

如何选择最近的日期,而不是在 php 数组中?

即假设我有一个数组

Array ( [0] => 21/07/2013 [1] => 22/07/2013 [2] => 23/07/2013 [3] => 24/07/2013 [4] => 25/07/2013 [5] => 26/07/2013 [6] => 27/07/2013 [7] => 28/07/2013 [8] => 29/07/2013 [9] => 30/07/2013 [10] => 04/08/2013 ) 

现在的日期是 20/07/2013

我需要检查数组,并且需要找到不在数组中的最近日期。即在这种情况下,日期21/07/2013 to 30/07/2013在数组中并且31/07/2013是最近的日期,我需要得到。

我怎么能?

4

1 回答 1

2

使用简单的 while 循环和 DateTime 类怎么样?

function getRecentDate(array $dates, $startDate) {
    // Set up some utilities
    $oneday = new DateInterval('P1D');
    $format = 'd/m/Y';

    // Build a DateTime object from the start date
    $date = DateTime::createFromFormat($format, $startDate);

    // Add one day and continue if date is in array
    do {
        $date->add($oneday);
        $str = $date->format($format);
    } while (in_array($str, $dates));

    // Return string representation of the date
    return $str;
}

$dates = array('21/07/2013', '22/07/2013', '23/07/2013', '04/08/2013'); 
echo getRecentDate($dates, '20/07/2013');  // output: 24/07/2013
于 2013-07-03T09:55:10.963 回答