Search code examples
phpmysqltimedate-math

Can't implement this timeAgo functionality in a PHP Loop


I'm trying to get PHP to show me some timeago functionality. I am looping through the results from a Mysql table where there is a column name called "aplicationdate" the format is "Y-m-d" in the database.. But it just shows me some negative large numbers like -16328.. Here is my timeago filev and any help would be greatly appreciated:

<? php

function timeAgo($time_ago) {
    $cur_time = date('Y-m-d');
    $time_elapsed = $cur_time - $time_ago;

    $days = round($time_elapsed / 86400);
    $weeks = round($time_elapsed / 604800);
    $months = round($time_elapsed / 2600640);
    $years = round($time_elapsed / 31207680);

    //Days
    if ($days <= 7) {
        if ($days == 1) {
            echo "yesterday";
        } else {
            echo "$days days ago";
        }
    }
    //Weeks
    else if ($weeks <= 4.3) {
        if ($weeks == 1) {
            echo "a week ago";
        } else {
            echo "$weeks weeks ago";
        }
    }
    //Months
    else if ($months <= 12) {
        if ($months == 1) {
            echo "a month ago";
        } else {
            echo "$months months ago";
        }
    }
    //Years
    else {
        if ($years == 1) {
            echo "one year ago";
        } else {
            echo "$years years ago";
        }
    }
}

?>

And here is how it's implemented in another file called profile.php, the timeago file is included in this one

 <? php

 $mysqli = new mysqli("localhost", "root", "", "cx");

 /* check connection */
 if ($mysqli - > connect_errno) {
     printf("Connect failed: %s\n", $mysqli - > connect_error);
     exit();
 }


 $idced_history = $_GET['idced'];

 $query = "SELECT * FROM applications WHERE idced='$idced_history'";

 if ($result = $mysqli - > query($query)) {

     while ($row = $result - > fetch_assoc()) {

         $curenttime = $row["applicationdate"];
         $time_ago = strtotime($curenttime);

         echo "<br><b>Applied On:</b> ".$row["applicationdate"]."  ".timeAgo($time_ago)."  <br>";


     }

     $result - > free();
 }

 $mysqli - > close();
?>

Solution

  • $cur_time is a string, not a number. It looks like you need to convert it to a Unix Timestamp before using it. So use time() instead of date():

     $cur_time  = time();
    

    (This is assuming $time_ago is also a Unix Timestamp)