简体   繁体   中英

How to get previous and next date compared to an array of dates in PHP

How to get previous and next date compared the current date to an array of dates. I have dates in string format to compare the current date and return previous and next date from dates

current date today like 16, Oct 2018 20:02

foreach($arraydates as $date) { 
    echo date('d, M Y H:i', $date) . '<br>';
}

output dates

02, Oct 2018 06:26<br>
09, Oct 2018 05:47<br>
18, Oct 2018 20:02<br>
24, Oct 2018 18:47<br>
31, Oct 2018 17:42<br>
07, Nov 2018 17:02<br> 

returning result should be like

09, Oct 2018 05:47<br>
18, Oct 2018 20:02<br>

Consider $arrayDates is ordered in ascending order.

<?php
$currentDate = strtotime("16, Oct 2018 12:00");
$prevDate;
$nextDate;

foreach($arrayDates as $date){
    $date = strtotime($date);
    if($date < $currentDate) {
        $prevDate = $date;
    }
    if($date > $currentDate){
        $nextDate = $date;
        break;
    }
}
?>

The previous date is stored in $prevDate and the next date is stored in $nextDate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM