2017-02-10 00:00:00
Run Code Online (Sandbox Code Playgroud)
我有一个日期数组
$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
);
Run Code Online (Sandbox Code Playgroud)
所以我必须编写一个函数,它可以返回上一个(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;
}
Run Code Online (Sandbox Code Playgroud)
但我无法理解如何编写返回上一个和下一个日期的函数
尝试这个,
$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"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
384 次 |
| 最近记录: |