将存储的纪元日期与 php 中的当前日期进行比较

Compare stored epoch Date to current Date in php

我正在制作一个 php 脚本,我将安排在每天 运行 上午 9 点。

我需要遍历数据库中卡片 table 中存储的所有详细信息。在每一行中,我都有一个 expirationDate 列,我需要检查该值是否在当前日期的 3 个月内,如果是,则发送电子邮件提醒用户他们的卡即将过期。如果到期日期在一个月内,他们还希望发送第二个提醒。

我遇到的问题是检查到期日期是否在当前日期的 3 个月内的比较逻辑。代码如下:

...
if ($Cards = mysqli_stmt_get_result($stmt)){
            while($row=mysqli_fetch_array($Cards))
            {    
                $email = $row['email'];
                $name = $row['Name'];
                $expDate = $row['expDate'];
                $reminderSent = $row['reminderSent'];
                $timeDiff = (intVal(time()) - intVal($expDate));
                echo "curDate is ". time() . " and expDate is ".$expDate. ". Difference is ".(intval(time()) - intVal($expDate));
                echo "<br>";

                //if ($timeDiff within3months){
                //    if ($reminderSent == 0) {
                //          //php code to send email
                //    }
                //    else if ($reminderSent == 1 && $timeDiff within1month){
                //          //php code to send email
                //    }     
                //}

            }
        }
...

我有一个想法,我也许可以找到 3 个月的纪元值并将其添加到我的到期日期 val 并检查 curDate 是否大于此值。这样的事情行得通吗?

E.G: $expDate + 5097600 > intVal(time())

如果有更好的方法来解决这个问题,请提出任何建议。

您使用 strtotime('-3 months'); 获得了三个月前日期的 unix 时间戳,并且可以将其与您在 $row['expDate'].

中的时间戳进行比较

另一种解决方案是在 SQL:

中进行比较
DATEDIFF(FROM_UNIXTIME(expDate), DATE_SUB(CURDATE(), INTERVAL 3 MONTH))
如果 expDate 在该范围内,

将为您提供正值,否则为负值。

不需要intVal() time() 函数。但是如果你想切换你最好的选择是 DateTime diff

$now = new DateTime();
$then = new DateTime($expDate);
$diff = $then->diff($now);
echo 'Difference is ' . $diff->format('%a days');