ii iml0sto1
ii iml0sto1

Reputation: 1742

Date difference won't work, datetime object

I am trying to get the difference between 2 dates in, years, months, days, hours and weeks.

But when I do it the object crash the page.

$row['timedate'] is a DateTime column from the database

$content_date = $row['timedate'];
$content_date = (new DateTime($content_date))->format('Y-m-d H:i:s');

$now_date = (new DateTime('now'))->format('Y-m-d H:i:s');

$since_start = $content_date->diff($now_date);

echo $since_start->days . ' days total<br>';
echo $since_start->y . ' years<br>';
echo $since_start->m . ' months<br>';
echo $since_start->d . ' days<br>';
echo $since_start->h . ' hours<br>';
echo $since_start->i . ' minutes<br>';
echo $since_start->s . ' seconds<br>';

If i echo $content_date its equal to 2019-02-25 01:44:51

If i echo $now_date its equal to 2019-02-25 02:29:32

Can someone tell me why this does not work?

Upvotes: 0

Views: 30

Answers (1)

Nick
Nick

Reputation: 147166

You should not be formatting $content_date and $now_date as strings if you want to use the DateTime::diff method. Instead, leave them as DateTime objects:

$content_date = new DateTime($content_date);

$now_date = new DateTime();

$since_start = $content_date->diff($now_date);

echo $since_start->days . ' days total<br>';
echo $since_start->y . ' years<br>';
echo $since_start->m . ' months<br>';
echo $since_start->d . ' days<br>';
echo $since_start->h . ' hours<br>';
echo $since_start->i . ' minutes<br>';
echo $since_start->s . ' seconds<br>';

Upvotes: 2

Related Questions