gpt4 book ai didi

php - 从日期数组中查找上一个和下一个最近的日期

转载 作者:可可西里 更新时间:2023-11-01 00:28:29 26 4
gpt4 key购买 nike

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"

关于php - 从日期数组中查找上一个和下一个最近的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55605043/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com