1

我从数据库中获得了一个 DATETIME,我需要能够检查该日期是否在从现在起 30 天内。

$renewal_date = $row['renewal_date'];
$current_time = new DateTime();
$interval = $renewal_date->diff($current_time);

这对我不起作用。

4

4 回答 4

2

Try something like this

$renewal_date = new DateTime($row['renewal_date']);
$cutoff= new DateTime('+31 days 00:00');


if ($renewal_date < $cutoff && $renewal_date >= new DateTime)
    echo 'Renewal Time!';
else
    echo 'All OK!';

Remove the && condition if you want to show renewal for dates in the past

于 2012-09-08T05:20:49.310 回答
0

Are you sure that $row['renewal_date'] is a DateTime object?

My impression is that this is a value that you take from a database rather than a DateTime object.

Try a var_dump($renewal_date) and if this is a string containing a date value, you should use something like:

$renewal_date = new DateTime ($row['renewal_date']);
$current_time = new DateTime();
$interval = $renewal_date->diff($current_time);
于 2012-09-08T05:15:56.353 回答
0

$renewal_date is not a PHP DateTime object. You can do var_dump($renewal_date); to verify this.

Check out the DateTime::diff manual for examples. You'll want to convert your date to a DateTime object using something like this:

$datetime1 = new DateTime($renewal_date);

Then it should work.

于 2012-09-08T05:16:06.873 回答
0
$renewal_date = strtotime($renewal_date); // maybe need it depending of sql format of date

if (abs($renewal_date - time()) < 86400*30)
{
    echo 'less than 30 days from now';
}

编辑 1

abs($renewal_date - time())给出了从现在开始的一段时间 ( time()),它应该指的是未来。事实上,这种情况也可以用于过去的时期......

< 86400*30说,过失肯定不及30天……

那是我的 2 美分:)

于 2012-09-08T05:15:07.303 回答