PHP在30分钟内基于两个时间戳返回结果

时间:2015-10-22 13:41:21

标签: php arrays datetime foreach timestamp

有点新手而且我被卡住了...所以任何帮助都会非常感激。

前言,我之前确实得到了一些帮助,这几乎达到了我所需要的水平,但它已经到了我不想再花费他更多时间的地步了(我问了很多他已经。)

我的基准时间是' am am'例如,我想检索30分钟的结果'过去'早上7点,目前在帮助下,我在早上7点之前和之后得到了所有结果。

以下是代码:

    $timeArrayOne = array(array("time"=>"2015-10-01 06:45:00"),array("time"=>"2015-10-01 07:15:00"),array("time"=>"2015-10-01 07:29:00"),array("time"=>"2015-10-01 07:31:00"));
    $msg = '';
    $closest = false;
    $closestResult = false;

        foreach ($timeArrayOne as $result) {
            // foreach to get $basetime
            $loggedTime = $result['time'];

            // Set Base time
            $baseTime = new DateTime("2015-10-01 07:00:00");

            // Set Time Two
            $TimeTwo = new DateTime($loggedTime);

            //  Subtract basetime from Time Two / divide by 60 for minutes
            $minutes = abs(strtotime($baseTime->format('Y-m-d H:i:s')) - strtotime($TimeTwo->format('Y-m-d H:i:s'))) / 60;

            if ($minutes <= 30) {
                $rounded = round($minutes);
                $msg .= "Success - $loggedTime <br/>";
                }
            }

            echo $msg;

提前致谢。

1 个答案:

答案 0 :(得分:1)

使用DateTime时,您不需要strtotime()和日期操作。您可以简单地比较DateTime对象,如下所示:

// Set the base time, which can also be read from input
$baseTime = new DateTime("2015-10-01 07:00:00");

// Add 30 (or any number) of minutes to it
$endTime = clone $baseTime;
$endTime->add(new DateInterval("PT30M"));    

foreach ($timeArrayOne as $result) {
    $loggedTime = $result['time'];
    $TimeTwo = new DateTime($loggedTime);
    if ($TimeTwo >= $baseTime and $TimeTwo <= $endTime) {
        $msg .= "Success - $loggedTime <br/>";
    }
}

echo $msg;

打印出来:

Success - 2015-10-01 07:15:00 
Success - 2015-10-01 07:29:00 

我认为这是预期的结果。

Demo

相关问题