Convert Timestamp to Time Ago using PHP

In this tutorial we will explain how to convert given date into a time ago string like 10 second(s) ago, 3 hour(s) ago, 1 month ago, 2 year(s) ago and decades. We are having a custom function to change a date format into time ago string. This is a very simple example, you can just copy paste and change according to your requirement.


Before you get started, take a look at the folders and files structure of PHP Time Ago Function
  • php-time-ago-function
    • css
      • style.css
    • images
    • templates
      • header.php
      • footer.php
    • function.php
    • index.php
Create HTML Form Date input. file named index.php

PHP Time Ago Function

">
PHP Custom Time Ago Function. file named function.php
 $unix_date) {   
        $difference = $now - $unix_date;
        $tense = "ago";
       
    } else {
        $difference = $unix_date - $now;
        $tense = "from now";
    }
   
    for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
        $difference /= $lengths[$j];
    }
   
    $difference = round($difference);
   
    if($difference != 1) {
        $periods[$j].= "(s)";
    }
   
    return "$difference $periods[$j] {$tense}";
}
?>
Create header.php and footer.php section of the webpage. The Bootstrap library is used to provide a better UI, so, include it in the header and footer section.
header.php



  
    
  
  
  
  
  
  
  
  
  PHP Time Ago Function | Web Haunt
  
  
  
  
  
  
  
   


  
  
footer.php