Get most recent date from an array of dates

后端 未结 11 719
小鲜肉
小鲜肉 2020-11-28 11:32

I have the array of dates below

array(5) { 
    [0]=> string(19) \"2012-06-11 08:30:49\" 
    [1]=> string(19) \"2012-06-07 08:03:54\" 
    [2]=> st         


        
11条回答
  •  天命终不由人
    2020-11-28 11:46

    I believe, following is the shortest code to find the recent date. you can alter it to find the index of the recent date or to find the recent in future or past.

    $Dates = array( 
    "2012-06-11 08:30:49", 
    "2012-06-07 08:03:54", 
    "2012-05-26 23:04:04",
    "2012-05-27 08:30:00",
    "2012-06-08 08:30:55",
    "2012-06-22 07:45:45"
    );
    
    $close_date = current($Dates);
    foreach($Dates as $date)
        if( abs(strtotime('now') - strtotime($date)) < abs(strtotime('now') - strtotime($close_date)))
            $close_date = $date;
    
    echo $close_date;
    

提交回复
热议问题