php - Time ago function accuracy -
i have function in gets date post , supposed write how long ago posted. when use function says posted 43 years , 4 months ago odd reason.
function relativetime($date,$precision=2) { $times=array(365*24*60*60 => "year", 30*24*60*60 => "month", 7*24*60*60 => "week", 24*60*60 => "day", 60*60 => "hour", 60 => "minute", 1 => "second"); $passed=time()-$date; if($passed<5) { $output='less 5 seconds ago'; } else { $output=array(); $exit=0; foreach($times $period=>$name) { if($exit>=$precision || ($exit>0 && $period<60)) break; $result = floor($passed/$period); if($result>0) { $output[]=$result.' '.$name.($result==1?'':'s'); $passed-=$result*$period; $exit++; } else if($exit>0) $exit++; } $output=implode(' , ',$output).' ago'; } return $output; }
i entering date using: $date = date("y-m-d h:i:s");
is $passed=time()-$date
off?
thanks everyone!
you using $date = date("y-m-d h:i:s");
input, return akin 2013-05-13 02:04:05
right now. call time()
return value near 1368403494
. subtract 2 eachother, , date string implicitly silently converted integer php, 2013
. means it'll see post 1368403494 seconds ago, not entirely accidentally ending somewhere in january 1970, start of unix timestamp age. yep, that'll 43 years , few months old.
don't mix string , integer arithmetic, php's silent conversions make them hell.
Comments
Post a Comment