检查日期数组中的日期并进行排列

时间:2012-10-26 05:47:42

标签: php

我有像这样的日期数组

$dates = array('2012-10-02','2012-10-03','2012-10-07', '2012-10-20');

现在,如果我有一个current_date说

$current_date = '2010-10-11';

我怎么能找到最近的PAST日期呢?在这种情况下将是2012-10-07

感谢

4 个答案:

答案 0 :(得分:1)

$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];

答案 1 :(得分: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";

答案 2 :(得分:0)

这也可以使用..

<?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;

答案 3 :(得分:0)

我的解决方案:

// 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]));
}

适用于所需日期之前和之后的日期。