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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s