Get Elapsed time(‘1 min ago’, ‘1 sec ago’, etc) from datetime

Many of the time we need to display the elapsed time from datetime field. This is mainly used in chatting system or in blog posting.

We can use the below function to get elapsed time:

     

function getTimeElapsedString($datetime, $full = false) {

$now = new DateTime(); // Current 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' => 'min', 's' => 'sec', ); 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';

}

we can call above function as

$string = getTimeElapsedString(‘2016-01-27 16:00:14’);

echo $string; // it will print 2 hours ago

Advertisements