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;
}
но я не могу понять, как я могу написать функцию для возврата как предыдущей, так и следующей даты
Попробуй это,
$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"
В соответствии с вашим массивом, пожалуйста, проверьте это, надеюсь, вам поможет
$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;
Возможный дубликат Как получить ближайшую дату по сравнению с массивом дат в PHP