Get most recent date from an array of dates in "Y-m-d H:i:s" format
Asked Answered
T

12

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?

Through answered 13/6, 2012 at 10:23 Comment(1)
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.Fronniah
T
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;
  }
}
Telemachus answered 13/6, 2012 at 10:29 Comment(4)
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.Telemachus
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 conditionTelemachus
I think it should be $curDate = date('Ymd',strtotime($date)); and not just $curDate = strtotime($date);Upend
@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 imhoTelemachus
E
96

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
Electromyography answered 13/6, 2012 at 11:1 Comment(0)
T
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;
  }
}
Telemachus answered 13/6, 2012 at 10:29 Comment(4)
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.Telemachus
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 conditionTelemachus
I think it should be $curDate = date('Ymd',strtotime($date)); and not just $curDate = strtotime($date);Upend
@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 imhoTelemachus
R
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];
Riparian answered 13/6, 2012 at 10:29 Comment(2)
+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(); });Lashonda
no need for date, just sort and get highest value: echo end(asort($dates));Nervy
O
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)));
Owenism answered 2/5, 2016 at 14:22 Comment(1)
That's nice, but care to explain what your code does?Gauldin
P
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);
Pardew answered 13/6, 2012 at 10:35 Comment(0)
T
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
Terri answered 13/6, 2012 at 10:29 Comment(0)
B
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;
}
Bear answered 13/6, 2012 at 10:31 Comment(0)
A
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;
Aboulia answered 13/6, 2012 at 11:15 Comment(0)
D
1

Try this:

public function getLargerDate(array $datas) {
    $newDates = array();
    foreach($datas as $data){
        $newDates[strtotime($data)] = $data;
    }
    return $newDates[max(array_keys($newDates))];
}
Detoxicate answered 8/4, 2015 at 18:54 Comment(3)
Rafael, SO is an English-speaking site. Please post portuguese answers for questions asked at pt.stackoverflow.com. :)Bushido
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'))){Parity
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.Bushido
B
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';
}
Begird answered 31/10, 2015 at 6:45 Comment(0)
F
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
Fronniah answered 21/1, 2022 at 8:46 Comment(0)
M
-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;
Melisma answered 19/5, 2015 at 8:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.