
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
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 |
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
1 2 3 |
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); |
Output
1 2 3 |
10 hours ago 10 hours ago 10 hours, 3 minutes, 58 seconds ago |
Script Download
Thanks friends
Your queries & suggestions are welcome in comments section
Please don’t forget to share if you find this helpful
Comments