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


PHP: Checking if a date is older then a year

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

我已经做了以下操作,但我确定我的逻辑不正确。

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

尝试如下:

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

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";
}

使用DateTime函数,解决此类问题要容易得多。

$checkDate = new 'DateTime('2013-01-01');
$pastDate = clone $aktDate;
$pastDate->modify('-1 year');
if($checkDate < $pastDate) {
    // Do something
}

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

您只需要在此处使用时间戳进行比较。

这样做:

if(strtotime($your_date) < strtotime('-1 year') ){
           echo "Date is older than year";
 }else{
           echo "Date is not older than year";
}

$your_date应采用datetime格式。