【问题标题】:Compare time and send notification in php比较时间并在php中发送通知
【发布时间】:2020-07-30 06:46:47
【问题描述】:

我的数据库中有一个设置表,我以小时为单位存储了 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;
    }
}

【问题讨论】:

    标签: php datetime time


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2018-02-09
      • 1970-01-01
      • 2023-02-22
      • 2015-09-15
      • 2023-03-07
      • 2013-02-13
      • 1970-01-01
      • 2011-08-13
      • 2011-09-03
      相关资源
      最近更新 更多