How to Show time ago like Facebook post in PHP
We will create a function for this and print the time with function name and it will convert the current timestamp and actual post_submitted timestamp difference.
<?php 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 &amp;lt;= 60){ return &quot;just now&quot;; } //Minutes else if($minutes &amp;lt;=60){ if($minutes==1){ return &quot;1 minute ago&quot;; } else{ return &quot;$minutes minutes ago&quot;; } } //Hours else if($hours &amp;lt;=24){ if($hours==1){ return &quot;an hour ago&quot;; }else{ return &quot;$hours hrs ago&quot;; } } //Days else if($days &amp;lt;= 7){ if($days==1){ return &quot;yesterday&quot;; }else{ return &quot;$days days ago&quot;; } } //Weeks else if($weeks &amp;lt;= 4.3){ if($weeks==1){ return &quot;a week ago&quot;; }else{ return &quot;$weeks weeks ago&quot;; } } //Months else if($months &amp;lt;=12){ if($months==1){ return &quot;a month ago&quot;; }else{ return &quot;$months months ago&quot;; } } //Years else{ if($years==1){ return &quot;1 year ago&quot;; }else{ return &quot;$years years ago&quot;; } } } ?>
After write this function we will have to call the function. First we will create a variable for date and then print it
$posted_time = "2020-27-02 20:20:20"; // For Print with timeago echo timeAgo($posted_time); // timeAgo is function which had created eariler and $posted_time is variable where time has been stored.