How to Converting timestamp to time ago in PHP
PHP Time Ago functionality is used to display time in a different format. The time ago format removes the problem of different time zones conversion. Given below is a function to do the time conversion. In this function, take the timestamp as an input and then subtract it from the current timestamp to convert it into the time ago format.
In this tutorial, we will learn How to Converting timestamp to time ago in PHP.
PHP CODE:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<?php // Time Elapsed String function timeElapsedString($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'; } ?> |
PHP Use example:
1 2 3 4 |
echo timeElapsedString('2021-11-27 19:34:30'); # timestamp input echo timeElapsedString('@1637998575'); echo timeElapsedString('2021-11-27 19:34:30', true); |
Output:
1 2 3 |
5 hours ago 5 hours ago 5 hours, 26 minutes, 31 seconds ago |