30

I have the array of dates in Y-m-d H:i:s format like:

array(5) { 
    [0]=> string(19) "2012-06-11 08:30:49" 
    [1]=> string(19) "2012-06-07 08:03:54" 
    [2]=> string(19) "2012-05-26 23:04:04" 
    [3]=> string(19) "2012-05-27 08:30:00" 
    [4]=> string(19) "2012-06-08 08:30:55" 
}

I would like to know the most recent date.

In other words, today is June 13th 2012, which datetime is closest to today's date?

From my sample array, I am expecting 2012-06-11 08:30:49.

How can I do that?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
sugarFornaciari
  • 313
  • 1
  • 3
  • 7
  • What does "_most recent date as in: the closest to today's date_" mean exactly? You want the most recent date that does not exceed the current date? Is this just a misunderstanding of your choice of English? All of your dates are before are earlier than your date of posting this question. – mickmackusa Jan 21 '22 at 08:28

12 Answers12

95

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
flowfree
  • 16,356
  • 12
  • 52
  • 76
33

Do a loop, convert the values to date, and store the most recent, in a var.

$mostRecent= 0;
foreach($dates as $date){
  $curDate = strtotime($date);
  if ($curDate > $mostRecent) {
     $mostRecent = $curDate;
  }
}

something like that... you get the idea If you want most recent BEFORE today :

$mostRecent= 0;
$now = time();
foreach($dates as $date){
  $curDate = strtotime($date);
  if ($curDate > $mostRecent && $curDate < $now) {
     $mostRecent = $curDate;
  }
}
PEM
  • 1,948
  • 14
  • 13
  • 1
    Converting dates to timestamps so that you have ints. then it's a simple int comparison, bigger = most recent. If your array is big, and your are looking for performances, then this is probably the simplest and fastest way. – PEM Jun 13 '12 at 10:38
  • Thank you, don't forget to validate the answer :) thank you By the way, if you want a date < as today, you can simply add a $now = time(); before the loop, and && $curDate < $now in the if condition – PEM Jun 13 '12 at 13:07
  • I think it should be $curDate = date('Ymd',strtotime($date)); and not just $curDate = strtotime($date); – Sam San Jan 31 '14 at 11:11
  • 1
    @IvorySantos I do not think we need the "date('Ymd',strtotime($date));" if we work with timestamps. Working with TS is better than with date strings imho – PEM Feb 03 '14 at 16:34
6

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];
FThompson
  • 28,352
  • 13
  • 60
  • 93
  • +1 With one modification, 'most recent' cannot be a future date or something aint quite right.. $dates = array_filter($dates, function($val) { return strtotime($val) < time(); }); – mschr Jun 27 '12 at 21:12
  • no need for date, just sort and get highest value: echo end(asort($dates)); – Jonathan Joosten Oct 25 '19 at 09:16
6
$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)));
Sumeet
  • 1,683
  • 20
  • 27
2

Thats my variant. It works with date in future.

$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-12 07:45:45"
);
$CloseDate = array();
$TimeNow = time();
foreach ($Dates as $Date) {
  $DateToCompare = strtotime($Date);
  $Diff = $TimeNow - $DateToCompare;
  if ($Diff < 0) $Diff *= -1;
  if (count($CloseDate) == 0) {
    $CloseDate['Date'] = $Date;
    $CloseDate['Diff'] = $Diff;
    continue;
  }
  if ($Diff < $CloseDate['Diff']) {
    $CloseDate['Date'] = $Date;
    $CloseDate['Diff'] = $Diff;
  }
}

var_dump($CloseDate);
AlexeyKa
  • 558
  • 3
  • 9
1

Here is my suggestion:

$most_recent = 0;

foreach($array as $key => $date){
    if( strtotime($date) < strtotime('now') && strtotime($date) > strtotime($array[$most_recent]) ){
        $most_recent = $key;
    }
}

print $array[$most_recent]; //prints most recent day
vinculis
  • 475
  • 3
  • 19
1
$arrayy = 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" 
);

function getMostRecent($array){
    $current = date("Y-m-d h:i:s");
    $diff1 = NULL;
    $recent = NULL;
    foreach($array as $date){
        if($diff = strcmp($current,$date)){
            if($diff1 == NULL){
                $diff1 = $diff;
                $recent = $date;
            }
            else{
                if($diff < $diff1){
                    $diff1 = $diff;
                    $recent = $date;
                }
            }
        }
    }
    return $recent;
}
Miqdad Ali
  • 6,129
  • 7
  • 31
  • 50
1

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;
FatalError
  • 922
  • 12
  • 31
1

Try this:

public function getLargerDate(array $datas) {
    $newDates = array();
    foreach($datas as $data){
        $newDates[strtotime($data)] = $data;
    }
    return $newDates[max(array_keys($newDates))];
}
Bruno Toffolo
  • 1,504
  • 19
  • 24
  • Rafael, SO is an English-speaking site. Please post portuguese answers for questions asked at http://pt.stackoverflow.com/. :) – Bruno Toffolo Apr 08 '15 at 19:22
  • 1
    Your answer always returns the 'maximum' date, not the maximum of dates that are earlier than today. You need the following line before you add to your $newDates array: if(strtotime($data) < strtotime(date('Y-m-j H:i:s'))){ – Warren Sergent Apr 08 '15 at 19:23
  • But "today" can be perfectly seen as "the most recent date, comparing to today". In this case I don't see any problem with his answer. – Bruno Toffolo Apr 08 '15 at 20:01
1

Try this works 100%

function getRecentDate($date_list,$curDate){
$curDate = strtotime($curDate); 
    $mostRecent = array();
    foreach($date_list as $date){                                             
       $diff = strtotime($date)-$curDate;
       if($diff>0){
        $mostRecent[$diff] = $date;
       }
    }   
    if(!empty($mostRecent)){
        ksort($mostRecent);            
        $mostRecent_key = key($mostRecent);
        if($mostRecent_key){
            return $mostRecent[$mostRecent_key];
        }
    }else{
        return false;
    }
}
$date_list = array('15-05-2015','14-01-2015','18-03-2015','20-10-2016','12-12-2014','12-12-2015');
$curDate = '14-01-2015';    
$get_recent = getRecentDate($date_list,$curDate);
if($get_recent){
    echo $get_recent;
}else{
    echo 'No recent date exists';
}
Anwar Hussain
  • 477
  • 3
  • 7
  • 18
1

After nearly 10 years and nearly 50,000 page views, it seems that no one could see the forest from the trees.

The array of datetime stamps is perfectly formatted for simple string comparison. There is absolutely NO reason to call anything other than max() to get the highest/latest string. Your Y-m-d H:i:s formatted values can be compared as strings because the unit integers are arranged from greatest magnitude to least magnitude. All integers are consistently zero-padded. There is literally no preparation required.

Code: (Demo)

$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 max($dates);
// 2012-06-11 08:30:49
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
-1
$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;