Php 如何确定日期是否超过当前日期的三个月
我正在以YYYY-MM-DD格式从mysql查询中获取日期 我需要确定从当前月份算起,过去是否超过三个月 我目前有以下代码:Php 如何确定日期是否超过当前日期的三个月,php,date,Php,Date,我正在以YYYY-MM-DD格式从mysql查询中获取日期 我需要确定从当前月份算起,过去是否超过三个月 我目前有以下代码: $passwordResetDate = $row['passwordReset']; $today = date('Y-m-d'); $splitCurrentDate = explode('-',$today); $currentMonth = $splitCurrentDate[1]; $splitResetDate = explode('-', $passwo
$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,那么$differenceimonths
将是-10,这不会通过if()语句
我如何修复此问题以允许上一年的几个月?
还是有更好的方法来完成整个例程?使用strotime()
,如下所示:
$today = time(); //todays date
$twoMonthsLater = strtotime("+3 months", $today); //3 months later
现在,您可以轻松地对它们进行比较和确定。我将在SQL表达式中进行日期比较 否则,PHP有一系列函数,可以轻松操作日期字符串:
我会使用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
}
您可以使用在MySQL中使用(编辑:)DATEDIFF()选择查询中的天数差异,但如果必须在PHP中执行此操作:如果OP需要更改重置间隔,会发生什么?或者如果OP更改了API不支持的数据库引擎DATEDIFF()
?OP必须重写SQL语句,而不是更改应用程序中的配置值。这就是为什么我还建议使用PHP日期时间函数的原因。这两种方法都有其警告。在本例中,他可能已经有了为其应用程序处理用户身份验证的存储过程,在这种情况下,在他的SQL语句中添加此功能(当然前提是此数据库引擎支持此功能)是很简单的。这是正常的,只有一个例外。$passwordExpiry行应为:$passwordExpiry=new DateInterval('P3M')代码>(您忘记了contstruct中的“P…”哦,很抱歉!很高兴你把它整理好了。