Minutes, Hours, Days from now, Time ago in words
Platform: PHP
Published Mar 02, 2012
Updated Feb 11, 2013
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:
- The number of hours and minutes if the object was posted within the day.
- The number of days if the object was posted within a month.
- The date if the object was posted over a month ago.
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 >= 31)
{
list($year, $month, $day) = split("-", $object[date]);
$date = date('M d, Y', @mktime(0, 0, 0, $month, $day, $year));
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;
}