Get most recent date from an array of dates

后端 未结 11 620
小鲜肉
小鲜肉 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;
    
    0 讨论(0)
  • 2020-11-28 11:48
    $dates = [
        "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" 
    ];
    echo date("Y-m-d g:i:s",max(array_map('strtotime',$dates)));
    
    0 讨论(0)
  • 2020-11-28 11:51

    Sort the array by date, and then get the front value of the array.

    $dates = array(5) { /** omitted to keep code compact */ }
    $dates = array_combine($dates, array_map('strtotime', $dates));
    arsort($dates);
    echo $dates[0];
    
    0 讨论(0)
  • 2020-11-28 11:56
    $DatesList = array( '2015-05-19', '2015-09-17', '2015-09-24', '2015-10-02', '2015-10-23', '2015-11-12', '2015-12-25' );
    
    $counter = 0; 
    $currentDate = date("Y-m-d");
    foreach ($DatesList as $dates)
    {
        if($dates >= $currentDate)
        {
            $storeDates[$counter] = $dates;
            $counter++;
        }
    }
    $closestDate = current($storeDates);
    echo $closestDate;
    
    0 讨论(0)
  • 2020-11-28 11:58

    Use max(), array_map(), and strtotime().

    $max = max(array_map('strtotime', $arr));
    echo date('Y-m-j H:i:s', $max); // 2012-06-11 08:30:49
    
    0 讨论(0)
提交回复
热议问题