首页 > 解决方案 > 比较时间并在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;
    }
}

标签: phpdatetimetime

解决方案


首先,我建议将约会的日期和时间存储在一个 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...
    }
}

推荐阅读