Hello

I'm Manmohanjit Singh and this is my WordPress powered blog. I'm currently in Malaysia. I go to school at SMK USJ 12. I'm a quiet guy but I'm not shy. I'll talk only when I need to.

@twitter

Twitter

  • Loading...

@manmohanjit

Now Playing

  • Loading...

manmohanjit1

# Posted x something ago; Twitter like timestamp using some PHP

by Manmohanjit Singh on Feb 16th, 2010 in Tutorial.

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”.

Tags:

No comments

  • No comments yet...

Leave A Comment

I'm watching you, please be nice and try not to spam. Comments are moderated. You can paste links directly, it will be formatted automatically. Basic XHTML tags are allowed.

Oh, I almost forgot. Comments are powered by Ajax, so don't hit the submit button twice. Thanks!

Wait for 15 seconds...