首页 > 解决方案 > 检查范围时间是否为新一天前后的 30 分钟

问题描述

我将日期和时间分别存储在表的不同列中。所以我试图检查当前时间是否比数据库中的时间早或晚了 30 分钟。

假设我有一个这样存储的日期和时间列表:

日期         |       时间
2020-05-29 00:10:00
2020-05-29 09:00:00

如果我当前的日期2020-05-28和时间是23:50:00,最近的日期和时间应该是2020-05-29, 00:10:00范围应该从的第一行2020-05-28, 23:35:00 - 2020-05-29, 00:35:00

我已经完成了代码,但它只能检测同一日期的时间范围。

$currentTime = time();
$minTime     = date("H:i", strtotime('-30 minutes', $currentTime));
$maxTime     = date("H:i", strtotime('+30 minutes', $currentTime));

// My query to get the list of date and time on one specific date and populate to $datetimeArr
// $sql = 'SELECT id, date, time FROM table WHERE date = "'.date('Y-m-d').'"';

$datetimeArr = [
    [
        'date' => '2020-05-29',
        'time' => '00:10:00'
    ],
    [
        'date' => '2020-05-29',
        'time' => '09:00:00'
    ],
];

foreach ($datetimeArr as $k => $row) {
    if($row['time'] >= $minTime && $row['time'] <= $maxTime) {
        $nearestDate = $row;
        continue;
    }
}

所以问题是,如果在新的一天之后的 30 分钟之前,我将无法正确获取范围。

标签: phpcodeigniterdatetimerange

解决方案


为什么不使用获取数据的 mysql 查询来执行此操作?这将比使用 php foreaches 更简单。

SELECT * FROM `TABLE` WHERE `time` > DATE_SUB(NOW(), INTERVAL 30 MINUTE) AND `time` < DATE_ADD(NOW(), INTERVAL 30 MINUTE)

为您的案例更新一个古怪的解决方案:

SELECT * from TableName where CONCAT(date, ' ', time) between DATE_SUB(NOW(), INTERVAL 30 MINUTE) and DATE_ADD(NOW(), INTERVAL 30 MINUTE)

这会将日期和时间字段连接成一个日期时间。


推荐阅读