我有这样的日期数组
$dates = array('2012-10-02','2012-10-03','2012-10-07', '2012-10-20');
现在如果我有一个 current_date 说
$current_date = '2010-10-11';
我将如何找到与此最近的过去日期。在这种情况下是 2012-10-07
谢谢
我有这样的日期数组
$dates = array('2012-10-02','2012-10-03','2012-10-07', '2012-10-20');
现在如果我有一个 current_date 说
$current_date = '2010-10-11';
我将如何找到与此最近的过去日期。在这种情况下是 2012-10-07
谢谢
$dates = array('2012-10-02','2012-10-03','2012-10-07', '2012,10,20');
$current_date = '2010-10-11';
if(!array_search($current_date, $dates))
array_push($dates, $current_date);
usort($dates, function($a1, $a2) {
return strtotime($a1) - strtotime($a2);
});
$my_current_date_index = array_search($current_date, $dates);
$my_previous_date = $my_current_date_index == 0 ? 'There is no previous date' : $dates[$my_current_date_index - 1];
像这样试试
$dates = array('2012-10-02','2012-10-03','2012-10-07', '2012-10-20');
echo "<pre>";
print_r($dates);
$dateArray=array();
foreach($dates as $row)
$dateArray[] = date('Y-m-d', strtotime($row));
$current_date = date('Y-m-d', strtotime('2012-10-11'));
array_push($dateArray,$current_date);
sort($dateArray);
echo "<br />";
print_r($dateArray);
echo "</pre>";
echo "<br />";
$cd_index= array_search($current_date, $dateArray);
if($cd_index>0)
{
$pastdate=$dateArray[$cd_index-1];
echo "Pastarray-".$pastdate;
}
else
echo "No Past Date";
未来日期:
if($cd_index<(count($dateArray)-1))
{
$pastdate=$dateArray[$cd_index+1];
echo "Pastarray-".$pastdate;
}
else
echo "No Future Date";
这个也可以用。。
<?php
$dates = array('2012-10-07','2012-10-02','2012-10-03', '2012,10,20');
$current_date = date('2010-10-11');
$closest='';
foreach($dates as $d)
{
if( date('y-m-d',strtotime($d))<$current_date && $d>$closest)
{
$closest=$d;
}
}
echo $closest;
我的解决方案:
// your test data
$dates = array('2012-10-02','2012-10-03','2012-10-07', '2012-10-20');
$current_date = '2012-10-11';
// array to help analyzing the file
$myResolver = array();
// processing the array and calculating the unixtimestamp-differences
array_walk($dates,'calc_ts', array(&$myResolver, $current_date));
// sorting the array
asort($myResolver);
// fetching the first (aka smallest) value
$closest = key($myResolver);
var_dump($closest);
// calculating the unixtimestam-differences
function calc_ts($item, $index, $d) {
$d[0][$item] = abs(strtotime($item) - strtotime($d[1]));
}
适用于您想要的日期之前和之后的日期。