Relative time function (example: 5 hours ago)

Bill

84.***.***.***
1,818 days ago

Relative time function (example: 5 hours ago)

Here's a simple relative time function which will let you echo the time since something happened (for example a new post or blog entry) in units of time from seconds and up to days.

PHP code:


define("CURRENT_TIME", time());

function relativeTime($time)
{
$shift = CURRENT_TIME-$time;

if ($shift < 45)
{
$diff = $shift;
$term = "second";
}
elseif ($shift < 2700)
{
$diff = round($shift / 60);
$term = "minute";
}
elseif ($shift < 64800)
{
$diff = round($shift / 60 / 60);
$term = "hour";
}
else
{
$diff = round($shift / 60 / 60 / 24);
$term = "day";
}

if ($diff != 1)
{
$term .= "s";
}

return "$diff $term";
}



To use it, just call the function and give it the timestamp you want to calculate, here's an example;

echo relativeTime($timestamp)." ago".