How to write a time ago function in mysqli using data from database?

Im a newbie in php. Any help will be appreciated.

MySQL already comes with a bunch of date/time functions built-in:

1 Like

i was thinking of how they do in facebook like , time ago function. though lol

this is just a matter of displaying a time difference. can help you with that as well.

yeah, i’ve been through a lot of sites to find this one, none of them is the one am looking for thats why im here sir! lol


$time_elapsed = timeAgo($time_ago); //The argument $time_ago is in timestamp (Y-m-d H:i:s)format.

//Function definition

function timeAgo($time_ago)
    $time_ago = strtotime($time_ago);
    $cur_time   = time();
    $time_elapsed   = $cur_time - $time_ago;
    $seconds    = $time_elapsed ;
    $minutes    = round($time_elapsed / 60 );
    $hours      = round($time_elapsed / 3600);
    $days       = round($time_elapsed / 86400 );
    $weeks      = round($time_elapsed / 604800);
    $months     = round($time_elapsed / 2600640 );
    $years      = round($time_elapsed / 31207680 );
    // Seconds
    if($seconds <= 60){
        return "just now";
    else if($minutes <=60){
            return "one minute ago";
            return "$minutes minutes ago";
    else if($hours <=24){
            return "an hour ago";
            return "$hours hrs ago";
    else if($days <= 7){
            return "yesterday";
            return "$days days ago";
    else if($weeks <= 4.3){
            return "a week ago";
            return "$weeks weeks ago";
    else if($months <=12){
            return "a month ago";
            return "$months months ago";
            return "one year ago";
            return "$years years ago";


So how do i use this with database, i got no idea, any help please

you get the timestamp out of the database and call the function with it. Although I would like to add that this function doesn’t handle leap years (which DateTime would offer).

1 Like

could you show me an example of leap year sir please/

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.