Minutes, Hours, Days from now, Time ago in words

By Hawkee on Mar 02, 2012

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

Comments

Sign in to comment.
Hawkee   -  Jun 09, 2012

@Jordyk19 Just pass the number of hours since the post was created.

 Respond  
Jordyk19   -  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.