Reputation: 351
2017-02-10 00:00:00
i have an array of date
$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
);
So i have to write a function it can return both previous(2016-12-01 12:00:00)
and next (2017-03-01)
date . How can i do this
I write function for compare dates
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;
}
but i cant understand how can i write function for returning both previous and next date
Upvotes: 3
Views: 894
Reputation: 2866
Try this,
$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';
$ts_date = strtotime($date); // timestamp of the date we are comparing
foreach( $date_array as $da ){
$ts_da = strtotime($da); // timestamp of the date from array
$ts_prev = strtotime($date_prev); // timestamp of the previous date
$ts_next = strtotime($date_next); // timestamp of the next date
if( $ts_da < $ts_date && ( !$ts_prev || $ts_prev < $ts_da ) )
$date_prev = $da;
if( $ts_da > $ts_date && ( !$ts_next || $ts_next > $ts_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"
Upvotes: 5
Reputation: 89
As per your array kindly check this, hope will helps you
$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;
Upvotes: 2