从“Y-m-d H:i:s”格式的日期数组中获取最新日期

2022-08-30 14:59:20

我有格式的日期数组,格式如下:Y-m-d H:i:s

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" 
}

我想知道最近的日期

换句话说,今天是 2012 年 6 月 13 日,哪个日期时间最接近今天的日期?

从我的样本数组中,我期待.2012-06-11 08:30:49

我该怎么做?


答案 1

使用 max()array_map()strtotime()。

$max = max(array_map('strtotime', $arr));
echo date('Y-m-j H:i:s', $max); // 2012-06-11 08:30:49

答案 2

执行循环,将值转换为日期,并将最新的值存储在 var 中。

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

类似的东西...你得到的想法,如果你想在今天之前:

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