2016-08-18 39 views
1

我有一个包含多个时间戳的数组。 我需要找到所有从最后30分钟的时间戳记在时间戳范围内找到集合

当前代码:

  //$history is a JSON decoded stream of arrays, of variable lengths 
      $hist = array(); 
      foreach($history as $newday){ 
        if($newday['Closed'] == $val){ 
          array_push($hist, $newday['Closed']); 
        } 
      } 
      var_dump($hist); 

样品阵列数据:

array(24) { 
    [0]=> 
    string(22) "2016-08-18T05:24:40.47" 
    [1]=> 
    string(23) "2016-08-14T11:43:25.917" 
    [2]=> 
    string(23) "2016-08-16T08:26:39.693" 
    [3]=> 
    string(23) "2016-08-18T04:51:45.553" 

如何计算/查找时间戳的最后30( $ hist)在PHP中?

回答

0

DateTime这个类很适合这种事情。

$timestamps = [ 
    "2016-08-18T05:24:40.47", 
    "2016-08-14T11:43:25.917", 
    "2016-08-16T08:26:39.693", 
    "2016-08-18T04:51:45.553", 
    "2016-08-18T16:30:45.553", 
]; 

$timeLimit = new DateTime('now'); 
$timeLimit->sub(new DateInterval('PT30M')); 

$recentTimestamps = []; 
foreach ($timestamps as $timestamp) { 
    $timestampDate = new DateTime($timestamp); 
    if ($timestampDate > $timeLimit) { 
     $recentTimestamps[] = $timestamp; 
    } 
} 

var_dump($recentTimestamps); 

输出:

array(1) { 
    [0] => 
    string(23) "2016-08-18T16:30:45.553" 
} 
0

这里给您一个提示:

strtotime("2016-08-18T05:24:40.47") >= strtotime('-30minutes')

试一试。