【问题标题】:PHP Return results based on two timestamps within 30minsPHP 根据 30 分钟内的两个时间戳返回结果
【发布时间】:2015-10-22 13:41:20
【问题描述】:

有点新手,我被困住了......所以任何帮助将不胜感激。

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

例如,我的基准时间是“早上 7 点”,我想检索“早上 7 点之后”的 30 分钟结果,目前在帮助下,我可以在早上 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;

提前致谢。

【问题讨论】:

  • 问题不清楚。请解释一下?
  • 我希望在 30 分钟的时间跨度内得到所有结果,而不是早于“早上 7 点”。
  • $minutes >= 0 在哪里?
  • 感谢 Paul,Amal 的回答非常出色,但感谢您的帮助。

标签: php arrays datetime foreach timestamp


【解决方案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

【讨论】:

    猜你喜欢
    • 2013-10-10
    • 1970-01-01
    • 2023-03-21
    • 2018-10-06
    • 2019-09-28
    • 2021-07-16
    • 2023-02-04
    • 1970-01-01
    • 2015-01-02
    相关资源
    最近更新 更多