PHP program to convert a given timestamp into time ago

PHPServer Side ProgrammingProgramming

To convert a given timestamp into time ago, the code is as follows −

Example

 Live Demo

<?php
function to_time_ago( $time )
{
   $difference = time() - $time;
   if( $difference < 1 )
   {
      return 'less than only a second ago';
   }
   $time_rule = array (
      12 * 30 * 24 * 60 * 60 => 'year',
      30 * 24 * 60 * 60 => 'month',
      24 * 60 * 60 => 'day',
      60 * 60 => 'hour',
      60 => 'minute',
      1 => 'second'
   );
   foreach( $time_rule as $sec => $my_str )
   {
      $res = $difference / $sec;
      if( $res >= 1 )
      {
         $t = round( $res );
         return $t . ' ' . $my_str .
         ( $t > 1 ? 's' : '' ) . ' ago';
      }
   }
}
echo "The timestamp to time ago conversion is ";
echo to_time_ago( time() - 600);
?>

Output

The timestamp to time ago conversion is 10 minutes ago

A function named ‘to_time_ago’ is defined that checks the difference between the time passed as parameter to the function and the time function. If this difference is found to be less than 1, it returns that the time passed just a second ago. Otherwise, the year, month, day, hour, minute, and second is generated in an array. A ‘foreach’ loop is used to iterate over the array previously generated. The time difference is computed and printed on the console.

raja
Published on 02-Jul-2020 06:50:01
Advertisements