Creating a Relative Time Function

Monday, August 17th, 2009

You've seen this sort of thing everywhere. It's the new "web 2.0 thing" to do (at least I think so). Instead of displaying the time formatted a certain way no matter how recent it was, you can have "posts about X minutes ago". It gives a new twist to how dates are normally formatted. In this tutorial I will show you how to create a simple PHP function that will accomplish this task for you.

PHP Time Example Image

PHP Time Example Image

Information You'll Need To Know

PHP's dates and times are represented in seconds since January 1, 1970. This means that one minute is represented by 60, hours as 3600 and one day is 86400. No, I don't memorize those, why do you think they made calculators? ;)

Try and get familiar with PHP's date function and ternary operators. We'll be using both and they're two things you really should know about.

Setup the Function

For the sake of easy recognition I'll be naming the function relativeTime. It will accept three parameters: the time to check, the cutoff before the date is formatted, and the format for the date if it meets the limit. The default for the limit is one day which seems pretty fair.

After we have declared the function, we want to set $time to the current time if it's empty or something other than a string or number. However, if it's not empty and a string (like "July 1, 1994 5:30") then apply strtotime and convert it to something date() can work with. Finally, set a variable to store the current time, and one to hold the return value.

<?php
function relativeTime($time = false, $limit = 86400, $format = 'g:i A M jS') {
if (empty($time) || (!is_string($time) && !is_numeric($time))) $time = time();
elseif (is_string($time)) $time = strtotime($time);

$now = time();
$relative = '';
}
?>

Is the $time right now?

The next step is to check weather or not the passed time is the current time. You can change "now" to anything you want, but I thought it would work.

if ($time === $now) $relative = 'now';

Or is it in the future?

Then we'll want to check if the time is in the future. The only time I can see this happening is when you have posts that are scheduled to go up.

elseif ($time > $now) $relative = 'in the future';

Nope, it's in the past.

After the two previous tests have failed, we are positive that the time to check is in the past. It's quite a chunk of code for this last part, but it pretty much repeats itself.

else {
$diff = $now - $time;

if ($diff >= $limit) $relative = date($format, $time);
elseif ($diff < 60) {
$relative = 'less than one minute ago';
} elseif (($minutes = ceil($diff/60)) < 60) {
$relative = $minutes.' minute'.(((int)$minutes === 1) ? '' : 's').' ago';
} else {
$hours = ceil($diff/3600);
$relative = 'about '.$hours.' hour'.(((int)$hours === 1) ? '' : 's').' ago';
}
}

return $relative;

First we need assign another variable that holds the difference (in seconds) between the date to check and now. If this new variable is greater than or equal to the limit parameter, set $relative to a formatted string. The next elseif statements checks to see if the difference is less than 60 seconds (one minute) and just sends back "less than one minute ago".

We then assign a new variable, $minutes, to the difference divided by 60 and rounded up. If $minutes is less than 60 (one hour), send back "X minute ago". If $minutes is not set to one, an s is appended to minute — this is done with the ternary operator.

The same process is used for the hours, only this time the difference is divided by 3600. Now does it make sense why I told you you will need to know that? ;)

We finish the function by returning $realtive, which now contains one of six options.

Conclusion

<?php
function relativeTime($time = false, $limit = 86400, $format = 'g:i A M jS') {
if (empty($time) || (!is_string($time) &amp;&amp; !is_numeric($time))) $time = time();
elseif (is_string($time)) $time = strtotime($time);

$now = time();
$relative = '';

if ($time === $now) $relative = 'now';
elseif ($time > $now) $relative = 'in the future';
else {
$diff = $now - $time;

if ($diff >= $limit) $relative = date($format, $time);
elseif ($diff < 60) {
$relative = 'less than one minute ago';
} elseif (($minutes = ceil($diff/60)) < 60) {
$relative = $minutes.' minute'.(((int)$minutes === 1) ? '' : 's').' ago';
} else {
$hours = ceil($diff/3600);
$relative = 'about '.$hours.' hour'.(((int)$hours === 1) ? '' : 's').' ago';
}
}

return $relative;
}
?>

This may seem like a simple function but it's very helpful. I recently coded up a quick Twitter widget for my friend (because I told her the default one was crap...) and she wanted to have the dates in relative time. I was lucky to have already had this function saved on my computer. Hope you enjoyed and learned something new!


If you enjoyed this article, you might consider subscribing to our rss feed to stay updated with all the latest tips and articles!

ABOUT THIS AUTHOR

Hey, I'm Vasili and I run duove.com. I love to code with PHP, MySQL, and jQuery, along with the basics like XHTML and CSS. At the moment, I just write (PHP) scripts for myself - like my CMS - but I hope that I can soon start freelancing for some people. Don't forget to follow me on Twitter for little tips and tricks I might tweet about. :)
  1. Cody
    August 17, 2009 at 4:32 pm
    • August 17, 2009 at 4:43 pm
  2. August 17, 2009 at 4:43 pm
  3. Kasper
    August 20, 2009 at 11:21 am
    • August 20, 2009 at 11:24 am
      • Kasper
        August 20, 2009 at 12:42 pm
  4. Kasper
    August 20, 2009 at 11:23 am
    • Kasper
      August 20, 2009 at 3:37 pm
  5. October 20, 2009 at 10:48 am
  6. November 5, 2009 at 12:38 pm
  7. November 5, 2009 at 12:41 pm
  8. November 5, 2009 at 1:16 pm
    • November 5, 2009 at 1:21 pm
  9. November 5, 2009 at 1:35 pm
  10. November 5, 2009 at 3:01 pm
  11. November 5, 2009 at 4:10 pm
  12. Kristian
    November 5, 2009 at 7:03 pm
  13. Kristian
    November 7, 2009 at 5:47 pm
    • November 7, 2009 at 9:27 pm
  14. nidhalbt
    December 30, 2009 at 4:48 am
  15. January 8, 2010 at 7:09 pm

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Popular Series

Output Buffering Articles
Build a Custom AJAX and PHP Contact Form
The Ultimate Image Gallery Manager.
ThemeForest Premium Site and WordPress Templates