Thursday, November 29, 2012

How to make user friendly date in PHP like time ago.

In new web 2.0 displays time and date not in old style style like 07 Jan 2000 12.30 pm. The new generation need relative time like 2 hours ago, 6 months ago, 4 years ago, very old etc. 

So if you save the timestamp of a particular content creation in database we can simply show this ‘ago time calculation’ using the following algorithm. I have create simple function for this :-

function TimeAgo($timestamp)
 $difference = time() - $timestamp;
 $periods = array("second", "minute", "hour", "day", "week", "month", "years", "decade");
 $lengths = array("60","60","24","7","4.35","12","10");
 for($j = 0; $difference >= $lengths[$j]; $j++)
  $difference /= $lengths[$j];
 $difference = round($difference);
 if($difference != 1) $periods[$j].= "s";
 $text = "$difference $periods[$j] ago";
 return $text;
To call this function you have to convert your datetime value in timestamp of PHP. foreg :-


No comments:

Post a Comment