Converting Timestamp to Time Ago in PHP Php by Rajesh Kumar Sahanee - September 2, 2022September 11, 20220 Post Views: 1,318 Hello Friends, Its being very long time I haven’t posted anything due to busy life schedule but today I have some free time to write a post and also a code which I had found over internet yesterday while working on a client’s project. In that project I had to show time in Ago format (i.e 1 month ago, 2 minutes ago, etc ) by converting Timestamp (YYYY-MM-DD HH:MM:SS) or Epoch timestamp. So Let’s start without wasting any time. Here is the Function index.php PHP function time_elapsed_string($datetime, $full = false) { $now = new DateTime; $ago = new DateTime($datetime); $diff = $now->diff($ago); $diff->w = floor($diff->d / 7); $diff->d -= $diff->w * 7; $string = array( 'y' => 'year', 'm' => 'month', 'w' => 'week', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second', ); foreach ($string as $k => &$v) { if ($diff->$k) { $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : ''); } else { unset($string[$k]); } } if (!$full) $string = array_slice($string, 0, 1); return $string ? implode(', ', $string) . ' ago' : 'just now'; } 12345678910111213141516171819202122232425262728 function time_elapsed_string($datetime, $full = false) { $now = new DateTime; $ago = new DateTime($datetime); $diff = $now->diff($ago); $diff->w = floor($diff->d / 7); $diff->d -= $diff->w * 7; $string = array( 'y' => 'year', 'm' => 'month', 'w' => 'week', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second', ); foreach ($string as $k => &$v) { if ($diff->$k) { $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : ''); } else { unset($string[$k]); } } if (!$full) $string = array_slice($string, 0, 1); return $string ? implode(', ', $string) . ' ago' : 'just now';} Usage Example index.php PHP echo time_elapsed_string('2022-09-02 00:22:35'); echo time_elapsed_string('@1662093103'); # epoch timestamp input echo time_elapsed_string('2022-09-02 00:22:35', true); 123 echo time_elapsed_string('2022-09-02 00:22:35');echo time_elapsed_string('@1662093103'); # epoch timestamp inputecho time_elapsed_string('2022-09-02 00:22:35', true); Output Output 10 hours ago 10 hours ago 10 hours, 3 minutes, 58 seconds ago 123 10 hours ago10 hours ago10 hours, 3 minutes, 58 seconds ago Script Download TimeAgo PHP Script 1 file(s) 1.76 KB Download Thanks friends Your queries & suggestions are welcome in comments section Please don’t forget to share if you find this helpful