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

时间:2015-01-22 12:23:26

标签: php

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

我做了以下但我确定我的逻辑不正确。

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

4 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:3)

试试这样:

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

答案 2 :(得分:1)

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

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

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

if($checkDate < $pastDate) {
    // Do something
}

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

答案 3 :(得分:0)

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

这样做:

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

$your_date应采用datetime格式。