Reputation: 95
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>
Upvotes: 1
Views: 206
Reputation: 114
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
Upvotes: 2