Reputation: 131208
In my MySQL table I have a datatime column (the time is saved in the following format 2011-02-15 11:01:14
). I extract this information with the PHP and print it to the user page.
$results = mysql_query($cmd,$link);
while ($res_array = mysql_fetch_array($results)) {
$submitted_at = $res_array['datetime'];
print $submitted_at."<br>";
}
However, I would like to show not only the given datatime, but also how long ago it was. In more detail, I need something like that: (67 day 4 hours 47 minutes 7 seconds ago
). Does PHP have some functions that can make it easier. In particular I bother with the fact that month could have 28, 29, 30 and 31 days.
As an alternative, I thought about doing it on the MySQL level. It should be easy to extract the number of second from the given time to the current data. Then I can easilly transform seconds into days, hours and minutes. But I do not know how can I access this information using the mysql_fetch_array
. Should it be something like $res_array['unix_timestamp(now())-unix_timestamp(datatime)']
?
Upvotes: 1
Views: 2525
Reputation: 2446
This'll be what you're looking for just change the formatting to suit your needs.
http://php.net/manual/en/datetime.diff.php
For example:
<?php
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days');
?>
Change this line:
$interval->format('%R%a days')
Following guidelines from here:
http://php.net/manual/en/function.date.php
Edit: This function is PHP 5.3+
Edit2 : Found this for older versions of PHP How to calculate the difference between two dates using PHP?
Upvotes: 3