【问题标题】:How to determine if a date is more than three months past current date如何确定日期是否超过当前日期三个月
【发布时间】:2013-07-22 16:08:39
【问题描述】:

我从 mysql 查询中获取日期,格式为 YYYY-MM-DD。

我需要确定这是否比当前月份过去超过三个月。

我目前有这个代码:

$passwordResetDate = $row['passwordReset'];
$today = date('Y-m-d');

$splitCurrentDate = explode('-',$today);
$currentMonth = $splitCurrentDate[1];

$splitResetDate = explode('-', $passwordResetDate);
$resetMonth = $splitResetDate[1];

$diferenceInMonths = $splitCurrentDate[1] - $splitResetDate[1];

if ($diferenceInMonths > 3) {
    $log->lwrite('Need to reset password');
}

问题在于,如果当前月份是 1 月,例如,给出月份值为 01,而 $resetMonth 是 11 月,则给出月份值为 11,那么 $differenceInMonths 将是 -10 ,它不会通过 if() 语句。

如何解决此问题以允许前一年的几个月? 或者有没有更好的方法来完成整个例程?

【问题讨论】:

标签: php date


【解决方案1】:

使用strtotime(),像这样:

$today = time(); //todays date 
$twoMonthsLater = strtotime("+3 months", $today); //3 months later

现在,您可以轻松比较它们并确定。

【讨论】:

    【解决方案2】:

    我会为此使用 PHP 的内置 DateTimeDateInterval 类。

    <?php
    
    // create a DateTime representation of your start date
    // where $date is date in database
    $resetDate = new DateTime($date);
    
    // create a DateIntveral representation of 3 months
    $passwordExpiry = new DateInterval('3M');
    
    // add DateInterval to DateTime
    $resetDate->add($passwordExpiry);
    
    // compare $resetDate to today’s date
    $difference = $resetDate->diff(new DateTime());
    if ($difference->m > 3) {
        // date is more than three months apart
    }
    

    【讨论】:

    • 这按原样工作,但有一个例外。 $passwordExpiry 行应为:$passwordExpiry = new DateInterval('P3M');(您忘记了构造中的“P”...)
    • 噢,对不起!很高兴你把它整理好了。
    【解决方案3】:

    我会在您的 SQL 表达式中进行日期比较。

    否则,PHP 有许多函数可以轻松操作日期字符串: PHP: Date/Time Functions - Manual

    【讨论】:

    • 如果 OP 需要更改重置间隔怎么办?或者如果 OP 更改了 API 不支持 DATEDIFF() 的数据库引擎?然后 OP 必须重写 SQL 语句,而不是更改其应用程序中的配置值。
    • 这也是我建议使用 PHP 日期时间函数的原因。任何一种方法都有其注意事项。在这种情况下,他可能已经有存储过程来处理他的应用程序的用户身份验证,在这种情况下,在他的 SQL 语句中添加这个功能将是微不足道的(当然前提是这个数据库引擎支持它)。跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    • 1970-01-01
    • 2019-03-03
    • 2012-05-22
    • 1970-01-01
    相关资源
    最近更新 更多