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

时间:2013-07-22 16:08:39

标签: php date

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

我需要确定从当月开始是否超过三个月

我目前有这段代码:

$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()语句。

如何解决这个问题,以便在过去一年中保留数月? 或者有更好的方法来完成这整个程序吗?

3 个答案:

答案 0 :(得分:1)

使用strtotime(),如下所示:

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

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

答案 1 :(得分:0)

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

答案 2 :(得分:-1)

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

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