2016-08-18 64 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')

試一試。