tags:

views:

835

answers:

5

hi everyone,

i am trying to convert a timestamp of the format: 2009-09-12 20:57:19 and turn it into something like '3 minutes ago' with php.

I found a useful script to do this, but I think its looking for a different format to be used as the time variable. The script I'm wanting to modify to work with this format is:

function _ago($tm,$rcs = 0) {

$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;

}

I think on those first few lines its trying to do something that looks like this (different date format math):

$dif = 1252809479 - 2009-09-12 20:57:19;

How would I go about converting my timestamp into that (unix?) format?

+6  A: 

Try strtotime().

Amber
the shortest and most helpful answer ever.
cosmicbdog
A: 

You'll have to take each individual piece of your timestamp, and convert it into Unix time. For example for the timestamp, 2009-09-12 20:57:19.

(((2008-1970)365)+(830)+12)*24+20 would give you a ROUGH estimate of the hours since January 1st, 1970.

Take that number, multiply by 60 and add 57 to get the minutes.

Take that, multiply by 60 and add 19.

That would convert it very roughly and inaccurately however.

Is there any reason you can't just take the normal Unix time to begin with?

is it better to store as a unix time in the sql table? I'm using mysqls automatic timestamp update currently on a timestamp column (which can be changed to unix). I'm just learning what is better?
cosmicbdog
Definitely. I believe the default for a mySQL table is the type you referenced, but Unix time is far more practical. You can always store it as an int.
Then again, Dav's solutions works well too. xD
A: 

strtotime() is your friend.

timdev
+1  A: 

Try this function its really fantastic, and simple

http://www.zachstronaut.com/posts/2009/01/20/php-relative-date-time-string.html

nepsdotin
A: 

Thanks for the nice code

p.karuppasamy