如何确定日期是否超过当前日期三个月


How to determine if a date is more than three months past current date

我正在从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');
}

这样做的问题是,例如,如果当前月份在一月,给出的月份值为01,而$resetMonth是十一月,给出的月值为11,那么$differenceInMonths将是-10,这将不会通过if()语句。

如何修复此问题以允许在前一年中使用数月?或者有更好的方法来完成整个程序吗?

使用strtotime(),如下所示:

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

现在,您可以很容易地对它们进行比较和确定。

为此,我会使用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
}

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

除此之外,PHP还有许多函数可以轻松地操作日期字符串:PHP:日期/时间函数-手动