Page 2 of 2
Re: facebook style "time ago" function
Posted: Mon Mar 08, 2010 3:42 am
by s.dot
Cool that is very valuable information. So I suppose when using lookup tables vs a bunch of if's (if worried about performance), it would depend on the number and complexity of the evaluations.
Of course, when profiling code, if this is the biggest speed problem then one is in great shape!
Re: facebook style "time ago" function
Posted: Mon Mar 08, 2010 9:58 am
by Luke
I should mention I took a lot of inspiration from Django's "humanize" for my code. So you could look at that as well.

Re: facebook style "time ago" function
Posted: Tue Aug 28, 2012 9:33 pm
by marcdonaldson
Hi everyone,
Here is my example of time_passed and it seems to perform quicker and also caters for different formats passed in and for time in the future
Code: Select all
/**
*
* This function calculates how long ago a certain
* date passed in was.
*
*/
define('SEC_IN_MINUTE',60); /* How many seconds are in a minute */
define('SEC_IN_HOUR',3600); /* How many seconds are in an hour */
define('SEC_IN_DAY',86400); /* How many seconds are in a day */
define('SEC_IN_WEEK',604800); /* How many seconds are in a week */
define('SEC_IN_MONTH',2630880); /* How many seconds are in a month */
define('SEC_IN_YEAR',31556926); /* How many seconds are in a year */
function md_time_passed($d) {
/**
* This code block checks to see what type of date is
* passed in and then obtains the difference in
* seconds.
*/
if (empty($d)) {
return('No date provided');
}
if ($d instanceof DateTime) {
$c = new DateTime();
$cTime = $c->getTimestamp();
$dTime = $d->getTimestamp();
$diff = $cTime-$dTime;
} elseif (is_array($d) && isset($d["mon"])) {
$d = $d[0];
$c = time();
$diff = $c-$d;
} elseif (is_string($d)) {
$d = strtotime($d);
$c = time();
$diff = $c-$d;
} else {
$c = time();
$diff = $c-$d;
}
$agostate = ($diff>=0) ? "ago" : "from now";
$diff = abs($diff);
/**
* This section of code converts the seconds in
* single units based on whether it is a year, month,
* week, day, hour, minute or second
*/
if ($diff>=SEC_IN_YEAR) {
$diff = floor($diff / SEC_IN_YEAR);
$suffix = "year";
} elseif ($diff>=SEC_IN_MONTH) {
$diff = floor($diff / SEC_IN_MONTH);
$suffix = "month";
} elseif ($diff>=SEC_IN_WEEK) {
$diff = floor($diff / SEC_IN_WEEK);
$suffix = "week";
} elseif ($diff>=SEC_IN_DAY) {
$diff = floor($diff / SEC_IN_DAY);
$suffix = "day";
} elseif ($diff>=SEC_IN_HOUR) {
$diff = floor($diff / SEC_IN_HOUR);
$suffix = "hour";
} elseif ($diff>=SEC_IN_MINUTE) {
$diff = floor($diff / SEC_IN_MINUTE);
$suffix = "minute";
} elseif ($diff>0) {
$suffix = "second";
} else {
return("Just Now");
}
return(($diff==1) ? "{$diff} {$suffix} {$agostate}" : "{$diff} {$suffix}s {$agostate}");
}
Please let me know your thoughts
Marc
Re: facebook style "time ago" function
Posted: Tue Aug 28, 2012 10:38 pm
by Benjamin
Looks great
