php - 检查范围时间是否为新一天前后的 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 分钟之前,我将无法正确获取范围。
解决方案
为什么不使用获取数据的 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)
这会将日期和时间字段连接成一个日期时间。
推荐阅读
- c++ - 继承构造函数的 C++ 可见性
- qt - QT的新风格铸造
- typescript - 如何在子类中更改扩展父类的属性类型
- javascript - 如何使用 minimist 打印使用帮助?
- python - 使用 cx_Freeze 从 Python 文件创建 exe 文件
- kubernetes - 为什么 Kubernetes v1.12 不再需要升级延迟?
- json - 在 typescript 中导入 json 文件导致带有有效 json 的“意外令牌”错误
- python - 如何在另一个 tk.button 功能运行时检查按钮按下?
- jackson - 在 Artemis UI 中使用 Json 消息发送字符串属性
- sql - 将列表日期存储在表和标签值中,以防基于 Postgresql 中的该表