Retrive time period like facebook

Posted: March 21, 2011 in How To, Programming, Tutorials
Tags: , ,

In facebook stream you’ll see the time period at the bottom of the stream. For example: 4 minutes ago, 2 days ago, 3 weeks ago…. In our recent project we have to show similar time fashion for our application’s activity stream. So I write a function to retrieve the time duration.

From twitter xml response got the date of the tweet. From the date i converted it into seconds from this method

 date_default_timezone_set('GMT');
 $tz = new DateTimeZone('Asia/Colombo');
 $datetime = new DateTime($status->created_at); //get the tweet created date send to DateTime php function 
 $datetime->setTimezone($tz);
 $time_display = $datetime->format('D, M jS g:ia T');
 $d = strtotime($time_display); //convert date string to second integer

After getting the data I just pass the created value in my function. Here is the function:

/*
 * @method: getTimeDuration
 * @param: unix timestamp
 * @return: duration of minutes, hours, days, weeks, months, years
 */
 function getTimeDuration($unixTime) {
 $period    =   '';
 $secsago   =   time() - $unixTime;
 
 if ($secsago < 60){
 $period = $secsago == 1 ? 'about a second ago'     : 'about '.$secsago . ' seconds ago';
 }
 else if ($secsago < 3600) {
 $period    =   round($secsago/60);
 $period    =   $period == 1 ? 'about a minute ago' : 'about '.$period . ' minutes ago';
 }
 else if ($secsago < 86400) {
 $period    =   round($secsago/3600);
 $period    =   $period == 1 ? 'about an hour ago'   : 'about '.$period . ' hours ago';
 }
 else if ($secsago < 604800) {
 $period    =   round($secsago/86400);
 $period    =   $period == 1 ? 'about a day ago'    : 'about '.$period . ' days ago';
 }
 else if ($secsago < 2419200) {
 $period    =   round($secsago/604800);
 $period    =   $period == 1 ? 'about a week ago'   : 'about '.$period . ' weeks ago';
 }
 else if ($secsago < 29030400) {
 $period    =   round($secsago/2419200);
 $period    =   $period == 1 ? 'about a month ago'   : 'about '.$period . ' months ago';
 }
 else {
 $period    =   round($secsago/29030400);
 $period    =   $period == 1 ? 'about a year ago'    : 'about '.$period . ' years ago';
 }
 return $period;
 
 }

Then in the view files I showed the data as:

<div class="period">
 <?=getTimeDuration($created);?> ago
</div>
If you need similar task instead of writing a new function again, you can use the above function.

 

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

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

Google photo

You are commenting using your Google 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 )

Connecting to %s