Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get most recent date from an array of dates

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?

like image 365
sugarFornaciari Avatar asked Jun 13 '12 10:06

sugarFornaciari


People also ask

How do I find the most recent date in an array?

push(new Date('2017/10/20')); let maxDate = dateArray[0]; for (let date of dateArray) { if (date > maxDate) { maxDate = date; } } console. log(`Max date = ${maxDate}`); Here, dateArray is an array of Date objects. maxDate is used to hold the largest Date object.

How do I sort a date in TypeScript?

To sort an array of objects by date in TypeScript: Call the sort() method on the array, passing it a function. The function will be called with 2 objects from the array. Subtract the timestamp of the date in the second object from the timestamp of the date in the first.


Video Answer


2 Answers

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 
like image 83
flowfree Avatar answered Sep 21 '22 15:09

flowfree


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;   } } 
like image 37
PEM Avatar answered Sep 21 '22 15:09

PEM