【问题标题】:find set within timestamp range在时间戳范围内查找集合
【发布时间】:2016-08-18 15:34:18
【问题描述】:

我有一个包含许多时间戳的数组。 我需要找到过去 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"

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

【问题讨论】:

    标签: php arrays time


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      在这里给你一个提示:

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

      试一试。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多