For
php, you can use array_reduce
to traverse once
$dates = ['2018-07-21','2018-08-13','2018-08-30','2018-9-02','2018-09-28','2018-11-02'];
$minSeconds = null;
$result = [];
array_reduce($dates, function($date1, $date2) use(&$minSeconds, &$result) {
if (empty($date1)) {
return $date2;
}
$date1Seconds = strtotime($date1);
$date2Seconds = strtotime($date2);
$seconds = $date2Seconds - $date1Seconds;
if ($minSeconds === null || $seconds < $minSeconds) {
$minSeconds = $seconds;
$result = [$date1, $date2];
}
return $date2;
}, null);
print_r($result);
Is
sorted? Then directly compare the two adjacent dates, from the beginning to the end to find out the minimum time difference on the line.
const arr=['2018-07-21','2018-08-13','2018-08-30','2018-9-02','2018-09-28','2018-11-02'];
function toDate(str){
const arr=str.split(/\D+/);
arr[1]-=1;
arr.unshift(Date);
const d=+new (Date.bind.apply(Date,arr))();
return d;
}
const timeArr=arr.map(toDate);
let min,index;
for(let i=0;i<timeArr.length-2;iPP){
const dur=timeArr[i+1]-timeArr[i];
if(min === undefined){
min=dur;
index=i;
}else if(min>dur){
min=dur;
index=i;
}
}
console.log(arr[index],arr[index+1]);
suppose your dates are sorted in order if you don't sort first
take advantage of sorting to make it easier to calculate by the way
var dtStart;
var dtEnd;
var tmDelta = -1;
['2018-07-21','2018-08-13','2018-08-30','2018-9-02','2018-09-28','2018-11-02'].sort(function($a, $b){
var tmA = (new Date($a)).getTime();
var tmB = (new Date($b)).getTime();
var delta = Math.abs(tmA - tmB);
if(tmDelta == -1 || delta > tmDelta)
{
tmDelta = delta;
dtStart = $a;
dtEnd = $b;
}
return tmA - tmB;
})
console.log(dtStart, dtEnd)
I'll have a PHP
$arr=['2018-07-21','2018-08-13','2018-08-30','2018-9-02','2018-09-28','2018-11-02'];
$data = [];
for ($i = count($arr)-1 ; $i >= 0; $i--) {
for ($j = 0; $j < $i ; $jPP) {
$a = $arr[$i];
$b = $arr[$j];
$v = date_diff(date_create($a), date_create($b)); //
// http://php.net/manual/zh/function.date-diff.php
//
// $data[$a.'-'.$b] = $v->format('%a');
$data[$v->format('%a')] = $a.'-'.$b;
}
}
echo "";
//$res = array_flip($data); //
ksort($data); //
var_dump(array_shift($data)); // string(20) "2018-9-02-2018-08-30"