【问题标题】:Compare stored epoch Date to current Date in php将存储的纪元日期与php中的当前日期进行比较
【发布时间】:2015-11-20 15:28:38
【问题描述】:

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

我需要遍历我数据库中卡片表中存储的所有详细信息。在每一行中,我都有一个 expireDate 列,我需要检查该值是否在当前日期的 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 个月的 epoch 值并将其添加到我的到期日期 val 中并检查 curDate 是否大于此值。这样的东西会起作用吗?

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

如果有更好的方法来解决这个问题,任何建议表示赞赏。

【问题讨论】:

    标签: php date epoch


    【解决方案1】:

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

    另一种解决方案是在 SQL 中进行比较:

    DATEDIFF(FROM_UNIXTIME(expDate), DATE_SUB(CURDATE(), INTERVAL 3 MONTH))
    

    如果expDate 在该范围内,则为您提供正值,否则为负值。

    【讨论】:

    • row['expDate'] 已经是一个时代,所以我不需要在那里使用 strtotime 对吗?
    • 哦,好吧,那我修改我的答案。你知道这些日期计算可以在 MySQL 中使用[DATEDIFF()](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_datediff) 非常高效地完成吗?
    • 类似于 SELECT DATE_FORMAT(expDate, '%m/%d/%Y') FROM cards WHERE expDate BETWEEN NOW() - INTERVAL 90 DAY AND NOW()
    • 是的,但我认为你必须使用DATE_SUB()。请注意三个月不是 90 天这一事实,尤其是在商业和法律方面。
    • 感谢您的帮助。我尝试 select DATE_DIFF(expDate, DATE_SUB(CURDATE, INTERVAL 3 MONTH)) as diffdate, ID, Name, WorkerID, pic, expDate FROM cards where diffdate > 0 但这告诉我 datediff 不是我的数据库中的表
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-15
      • 2016-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-24
      相关资源
      最近更新 更多