P. Nick
P. Nick

Reputation: 991

DateTime not working: See if date is older than 30 days

For some reason that I'm not fully aware of, this isn't working. I want to prevent certain things if the date of a published article is older than 30 days, where fetchData["article_date"] in the database is 2015-09-08 15:18:27

 $new = new DateTime(date('Y-m-d H:i:s'));
 $old = new DateTime($fetchData["article_date"]);
 if(strtotime($old->modify('+30 days') < $new)) { 

    // Older than 30 days

  }

Help is appreciated.

Upvotes: 1

Views: 452

Answers (3)

Anurag Verma
Anurag Verma

Reputation: 495

Your if condition is wrong

the modify function produces an object and you can directly compare it with your $new which is an object as well.

$new = new DateTime(date('Y-m-d H:i:s'));
$old = new DateTime($fetchData["article_date"]);


 if($old->modify('+30 days') < $new) { 

    echo "hello";

  }

Upvotes: 1

Keyne Viana
Keyne Viana

Reputation: 6202

Just an example

$new = new DateTime(date('Y-m-d H:i:s'));
$old = new DateTime('2015-12-22 15:18:27');
$interval = $old->diff($new);

if($interval->format('%a') > 30) {

}

Upvotes: 3

Rajdeep Paul
Rajdeep Paul

Reputation: 16963

To know if the date of a published article is older than 30 days, you can do something like this:

$new = new DateTime(date('Y-m-d H:i:s'));
$old = new DateTime($fetchData["article_date"]);
if($old->modify('+30 days')->getTimestamp() < $new->getTimestamp()) { 
    // older than 30 days
}

Upvotes: 1

Related Questions