[英]How to determine if a date is more than three months past current date
I am getting a date back from a mysql query in the format YYYY-MM-DD. 我从mysql查询中以YYYY-MM-DD格式返回日期。
I need to determine if that is more than three months in the past from the current month. 我需要确定距当前月份过去三个月以上。
I currently have this code: 我目前有以下代码:
$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');
}
The problem with this is that, if the current month is in January, for instance, giving a month value of 01, and $resetMonth
is November, giving a month value of 11, then $differenceInMonths
will be -10, which won't pass the if() statement. 这样的问题是,例如,如果当前月份是一月,则给定月份值01,而
$resetMonth
是11月,给定月份值11,则$differenceInMonths
将为-10,这不会传递if()语句。
How do I fix this to allow for months in the previous year(s)? 如何解决此问题,以便在上一年中保留数月? Or is there a better way to do this entire routine?
还是有更好的方法来完成整个例程?
Use strtotime()
, like so: 使用
strtotime()
,如下所示:
$today = time(); //todays date
$twoMonthsLater = strtotime("+3 months", $today); //3 months later
Now, you can easily compare them and determine. 现在,您可以轻松地比较它们并确定。
I'd use PHP's built-in DateTime
and DateInterval
classes for this. 为此,我将使用PHP的内置
DateTime
和DateInterval
类。
<?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
}
I would do the date comparison in your SQL expression. 我会在您的SQL表达式中进行日期比较。
Otherwise, PHP has a host of functions that allow easy manipulation of date strings: PHP: Date/Time Functions - Manual 否则,PHP具有许多功能,可轻松操作日期字符串: PHP:日期/时间函数-手册
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.