php - 比较时间并在php中发送通知
问题描述
我的数据库中有一个设置表,其中我以小时为单位存储了 notification_time
设置:
notification_time
3
现在我有一个约会表,其中保存了 id(int(11))、name(varchar(50))、date(varchar(50))、start_time(varchar(50))
预约:
id | name | date | start_time
1 Amit 2020-07-31 06:15:00
2 Pawan 2020-08-01 13:30:00
现在我想发送 start_time 小于 2 小时(即开始时间前 2 小时)的通知,因为我已经编写了以下脚本,但问题是时间过去后它也在发送邮件通知,并且与当前时间的比较是不合适。
$current_time = date("Y-m-d H:i:s");
foreach ($appointmentData as $rowAppointment) {
$diff_in_sec = round(abs(strtotime($current_time) - strtotime($rowAppointment->date . ' ' . $rowAppointment->start_time)));
$number_of_hours = 3600 * $settings->notification_time;
if ($diff_in_sec >= $number_of_hours) {
send notification;
}
}
解决方案
首先,我建议将约会的日期和时间存储在一个 DATETIME 类型的字段中(在 MySQL 中)。我会使用 PHP 的 DateTime-Class [https://www.php.net/manual/en/class.datetime.php] 和 DateInterval-Class [https://www.php.net/manual/en/class。 dateinterval.php] 用于计算。两者都使解决方案更容易。
例如:
$now = new \DateTime();
foreach ($appointments as $appointment) {
// expecting that $appointment->start is already a DateTime-Object
$diff = $now->diff($appointment->start);
// with 'a' checking if there are zero days difference between the two datetimes, with 'h' checking
if ($diff->format('a') == 0 && $diff->format('h') <= $settings->notification_time) {
// send notification...
}
}
推荐阅读
- intellij-idea - IntelliJ 远程调试 gradle 项目无法附加源
- javascript - WebSocket 响应作为具有多条消息问题的 Promise
- reactjs - 将 React Native 从 0.57 升级到 0.58.5
- c# - 修改了带有 Monitor Collection 的 C#;枚举操作可能无法执行
- three.js - 如何使 CSS2DRenderer 标签表现得像 SpriteMaterial 一样用于缩放对象与父母?
- nativescript - 以编程方式添加新事件时,RadCalendar 不更新事件
- javascript - 排毒 textInput 不写文本
- google-apps-script - 如何根据另一列中的另一个值是否存在匹配来设置单元格的值?
- oracle - 如何将字符串列表传递给 Olracle 中的存储过程
- node.js - Heroku 上的 Redis 连接错误:127.0.0.1 而不是 REDIS_URL