从日期数组中查找上一个和下一个最近的日期

时间:2019-04-10 05:04:54

标签: php date

2017-02-10 00:00:00

我有一个日期数组

$date_array=array
(
    [0] => 2015-09-01 12:00:00
    [1] => 2015-12-01 12:00:00
    [2] => 2016-03-01 12:00:00
    [3] => 2016-06-01 12:00:00
    [4] => 2016-09-01 12:00:00
    [5] => 2016-12-01 12:00:00
    [6] => 2017-03-01 12:00:00
    [7] => 2017-06-01 12:00:00
    [8] => 2017-09-01 12:00:00
    [9] => 2017-12-01 12:00:00
    [10] => 2018-03-01 12:00:00
    [11] => 2018-06-01 12:00:00
    [12] => 2018-09-01 12:00:00
    [13] => 2018-12-01 12:00:00
    [14] => 2019-03-01 12:00:00
    [15] => 2019-06-01 12:00:00
    [16] => 2019-09-01 12:00:00
    [17] => 2019-12-01 12:00:00
    [18] => 2020-03-01 12:00:00
    [19] => 2020-06-01 12:00:00
);

所以我必须编写一个函数,它可以返回上一个(2016-12-01 12:00:00)和下一个(2017-03-01)日期。我该怎么做

我编写了比较日期的功能

function dif_date($date_1, $date_2) {
    $first= $date_1;
    $createDate = new DateTime($first);
    $strip = $createDate->format('Y-m-d');
    $difference = $date_2->diff($createDate, true);
    $difference->total_difference = $difference->y . "." . $difference->m;
    return $difference;
}

但是我不明白如何编写用于返回上一个和下一个日期的函数

2 个答案:

答案 0 :(得分:5)

尝试一下

$date_array = array
    (
    '2015-09-01 12:00:00',
    '2015-12-01 12:00:00',
    '2016-03-01 12:00:00',
    '2016-06-01 12:00:00',
    '2016-09-01 12:00:00',
    '2016-12-01 12:00:00',
    '2017-03-01 12:00:00',
    '2017-06-01 12:00:00',
    '2017-09-01 12:00:00',
    '2017-12-01 12:00:00',
    '2018-03-01 12:00:00',
    '2018-06-01 12:00:00',
    '2018-09-01 12:00:00',
    '2018-12-01 12:00:00',
    '2019-03-01 12:00:00',
    '2019-06-01 12:00:00',
    '2019-09-01 12:00:00',
    '2019-12-01 12:00:00',
    '2020-03-01 12:00:00',
    '2020-06-01 12:00:00',
);

$date_prev = '';
$date_next = '';
$date = '2017-02-10 00:00:00';

foreach($date_array as $da){
    if(strtotime($da) < strtotime($date))
        if(!strtotime($date_prev) || strtotime($date_prev) < strtotime($da))
            $date_prev = $da;
    if(strtotime($da) > strtotime($date))
        if(!strtotime($date_next) || strtotime($date_next) > strtotime($da))
            $date_next = $da;
}

var_dump($date_prev); //string(19) "2016-12-01 12:00:00"
var_dump($date_next); //string(19) "2017-03-01 12:00:00"

答案 1 :(得分:2)

请根据您的阵列进行检查,希望会对您有所帮助

    $custom = '2020-03-01 12:00:00';
    $dates[] = $custom;
    $dates = array_unique(array_values($dates));
    asort($dates);
    $searched = array_search($custom, $dates);
    $past = $searched-1; $next = $searched+1;

    $pastDate = 'notfound';
    if(array_key_exists($past, $dates)) $pastDate = $dates[(int)($searched-1)]; 

    $nextDate = 'notfound';
    if(array_key_exists($next, $dates)) $nextDate = $dates[(int)($searched+1)];


    echo $pastDate." - ".$nextDate;