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;
}

Comments

Sign in to comment.
Hawkee   -  Jun 09, 2012
@Aha2Y Just pass the number of hours since the post was created.
 Respond  
Aha2Y   -  Jun 09, 2012
How can i use this in a plain PHP script, Without MYSQL?
 Respond  
ulquiorra4   -  Mar 04, 2012
^_^
 Respond  
GuitarMasterx7   -  Mar 03, 2012
ohnice. good stuff ;o
 Respond  
Fawkes   -  Mar 03, 2012
Good job Hawke, We've messing with it all days.. :D
 Respond  
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.