Some sites like Youtube use a simple formatting style in comments’ date & times. Instead of writing long and detailed dates (like October 12, 2009 07:23 PM) , they use relative dates like 3 days ago, 2 weeks ago, etc.
The code below does the same thing. It takes your date,in any format php’s strtotime uses (which means, in most situations dates coming from your database can be used directly), and converts it into this simle format.
Click here for turkish version
/**
* finds passed time in a readable format like
* "2 days ago", "5 years ago", etc...
* Sample usage:
* echo relativeTime("2009-08-23 12:05:14");
* @param str $dateStr date to calculate. any format readable by
* php's strtotime function is appropriate.
* check out http://www.php.net/manual/tr/function.strtotime.php
* for usage of strtotime.
* @param str $now default is null which means running time. this is the
* bigger date which $dateStr is substracted from.
* @return str
*/
function relativeTime($dateStr, $now=null){
if(!$now) $now=time();
$time=$now-strtotime($dateStr);
if($time<0) return "";
if($time<60){$no=$time; $str="second";}
else if($time<3600){$no=$time/60; $str="minute";}
else if($time<86400){$no=$time/(3600); $str="hour";}
else if($time<86400*7){$no=$time/(86400); $str="day";}
else if($time<86400*30){$no=$time/(86400*7); $str="week";}
else if($time<86400*365){$no=$time/(86400*30); $str="month";}
else {$no=$time/(86400*365); $str="year";}
return round($no)." ".$str.((round($no)>1)?"s":"")." ago";
}

Comments