PHP:检查日期是否早于一年

emm*_*ins 3 php

我有一个从数据库中提取的日期。我想检查该日期是否超过一年。

我已完成以下操作,但我确定我的逻辑不正确。

if (strtotime($horsesplaced1['Date']) < strtotime('-1 year')) {
    //true
    $placed .= "/";
    $stopyear = "yes";
}
Run Code Online (Sandbox Code Playgroud)

Pri*_*ank 8

像这样尝试:

<?
$dbDate = '2014-01-20 17:14:40';
if(strtotime($dbDate)<strtotime('-1 year')){
 echo "YES";
}else{
echo "NOP";
}
?>
Run Code Online (Sandbox Code Playgroud)


Pay*_*tey 6

PHP DateTime 对此更加有用。就像是:

$new = new DateTime('2015-01-01');
$old = new DateTime('2013-01-01');

if ( $old->modify('+1 year') < $new) {
    echo "More than a year ago";
}
Run Code Online (Sandbox Code Playgroud)


Ren*_*hle 1

使用DateTime函数可以更轻松地解决此类问题。

$checkDate = new \DateTime('2013-01-01');

$pastDate = clone $aktDate;
$pastDate->modify('-1 year');

if($checkDate < $pastDate) {
    // Do something
}
Run Code Online (Sandbox Code Playgroud)

我不知道您是否使用日期时间字段/对象。如果您有日期时间对象,则可以直接使用它们。