Posted x something ago; Twitter like timestamp using some PHP

Have you used or seen Twitter? The cool way they display the time a tweet was posted on? Example: “8 minutes ago”. I don’t know if you think its cool or not, but I sure think it is.

I have been finding this piece of code either ready for me to use or even a tutorial. I came across the code at snipplr, a place where you can share your code. It’s a useful site, that I suggest you bookmark. Anyway, it uses the time() format to calculate the seconds/minutes/hours/days/years/decades ago. You can view the code here.

function newTime($tm,$rcs = 0) {
	// http://snipplr.com/view/17338/
	$cur_tm = time(); $dif = $cur_tm-$tm;
	$pds = array('second','minute','hour','day','week','month','year','decade');
	$lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600);
	for($v = sizeof($lngh)-1; ($v >= 0)&&(($no = $dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm-($dif%$lngh[$v]);
	$no = floor($no); if($no <> 1) $pds[$v] .='s'; $x=sprintf("%d %s ",$no,$pds[$v]);
	if(($rcs == 1)&&($v >= 1)&&(($cur_tm-$_tm) > 0)) $x .= time_ago($_tm);
	return $x."ago";
}

To use it, echo newTime(1264837797);. It’ll return “56 minutes ago”.

CommentsRefresh

No comments on this page yet...

Post A Comment




Thank you, your comment has been posted.

Log In »
X
-

Log In