How to show time in Day, Hours & Minutes ago

Hello,

What is the best way to show the time difference between now and what is stored on the MySQL DB in Day, Hours & Minutes ago.

That is say MySQL time for message posted is: “2012-07-17 15:30:17”

So then what is the best Php code for showing time diff between now and this date & time this way:

This message was posted: X days, Y Hours & Z Minutes ago

ThanX

You want to use DateTime::diff

<?php
$datetime1 = new DateTime(); // Today's Date/Time
$datetime2 = new DateTime('2012-07-17 15:30:17');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%D days %H hours %I minutes ago');
?>

I am not using OO Php.
Can you give me the code in Procedural style?

Also please state how to get the date & time from server and then to compared this to date & time field of the MySQL DB?

ThanX,

The code I posted does both of those. Yes, it is OOP use of DateTime(), but you can just throw it into any portion of your code without any issues. If you desperately do not want to use DateTime as an object, you can use

$result = date_diff(date(), date('2012-07-17 15:30:17'));
echo date_format($result, '%D days %H hours %I minutes ago');

Actually, I am not sure this will work

echo date_format($result, '%D days %H hours %I minutes ago');

As it seems date_diff returns DateInterval object, so you may have to use $result->format(‘%D days %H hours %I minutes ago’);

Hi,

I am getting Error message:

Fatal error: Call to undefined function date_diff()

Check your version of PHP with what the manual says

It is Php Version 5.1.4

Does this version of Php have the function date_diff() or does one need to load it separately via in include?

No, you don’t have the ability to use date_diff. You may want to read through this thread (one of them shows how to return it in your database query)