简体   繁体   English

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

[英]PHP: Checking if a date is older then a year

I have a date I'm pulling from my database. 我有一个日期要从数据库中提取。 I want to check if that date is over a year old. 我想检查一下这个日期是否超过一年。

I have done the following but I'm sure my logic is incorrect. 我已完成以下操作,但我确定我的逻辑不正确。

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

Try like this: 尝试这样:

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

PHP DateTime is far more useful for this. PHP DateTime对此更为有用。 Something like: 就像是:

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

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

With the DateTime functions its much easier to solve such problems. 使用DateTime函数可以更轻松地解决此类问题。

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

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

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

I don't know if you work with a datetime field/object. 我不知道您是否使用日期时间字段/对象。 If you have a datetime object you can work directly with them. 如果您有日期时间对象,则可以直接使用它们。

You just need to compare using timestamp here. 您只需要在此处使用时间戳进行比较。

Do like this: 这样做:

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

$your_date should be in datetime format. $your_date应该采用datetime格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM