Time ago Script in PHP
In this tutorial, we will learn converting timestamp to time ago using the PHP function.
DateTime convert Time Ago
Just now
2 seconds ago
1 week ago
1 minute ago
1 month ago
1 year ago
First, create a timeAgo function then use the timeAgo function will convert the timestamp to the time ago.
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 32 |
<?php function timeAgo($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 $key => &$val) { if ($diff->$key) { $val = $diff->$key . ' ' . $val . ($diff->$key > 1 ? 's' : ''); } else { unset($string[$key]); } } if (!$full){ $string = array_slice($string, 0, 1); } return $string ? implode(', ', $string) . ' ago' : 'just now'; } ?> |
Usage Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php echo timeAgo('2022-08-12 11:38:43'); echo timeAgo('2021-05-19 11:38:43', true); echo timeAgo('2011-10-11'); echo timeAgo('2009-01-20', true); //timestamp echo timeAgo('@1598867187'); echo timeAgo('@1598867187', true); // html $join_date = '2021-11-29 11:38:43'; echo '<div title="'.$join_date.'">'.timeAgo($join_date).'</div>'; ?> |