This will take the date and time posted of an object in mySQL and convert it to a human readable form through PHP. It has 3 different modes of displaying the age:
It uses the mySQL timediff() function to determine the number of hours since the object was added. This requires either a datetime field or concatenated date and time fields. You need to pass the PHP function this value to get a human readable form. For example:
select timediff(concat(curdate(), ' ', curtime()), concat(date, ' ',time)) as hours ...
The results will look like this:
a few seconds ago
1 min ago
5 mins ago
2 hours 3 mins ago
3 days ago
Jan 20, 2012
function get_age($hours)
{
list($hour, $min, $sec) = split(":", $hours);
if($hour > 24) $days = round($hour / 24);
else $days = 0;
if($days >= 61) {
$date = date('M d, Y', strtotime("-$hour hours"));
return $date;
}
else if($days >= 1) {
$age = "$days day";
if($days > 1) { $age .= "s"; }
}
else {
if($hour > 0) {
$hour = ltrim($hour, '0');
$age .= " $hour hour";
if($hour > 1) { $age .= "s"; }
}
if($min > 0) {
$min = ltrim($min, '0');
if(!$min) $min = '0';
$age .= " $min min";
if($min != 1) { $age .= "s"; }
}
}
if($min < 1 and $hour < 1) { $age = 'a few seconds'; }
$age .= ' ago';
return $age;
}