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
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) && !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!
Article Sponsored by:
PHP for Absolute Beginners is written for the complete novice; no previous coding knowledge is assumed, and all concepts are explained to ensure maximum understanding.








For your first IF statement you have
if (emptyempty($time) || (!is_string($time) && !is_numeric($time)))
Shouldn’t it be
if (empty(empty($time) || (!is_string($time) && !is_numeric($time)))
Added a “(” After the first empty.
Hi Cody,
Thanks for pointing that out, I believe it is just an issue with our syntax highlighting plugin. It is duplicating the empty function call, so there should be only one call to empty
cool! ive done one myself but ill check this one
Hmm,
I can’t get this to work I got a timestamp from a mysql database looks like 1250182173 but when I insert this as the first parameter and leave the others relativeTime(1250182173);
I just all my stuff to now.
Any suggestions?
Try doing this:
<?php
$date = relativeTime(strtotime(MYSQL_DATE_GOES_HERE));
?>
Then it just says now at all my posts
Or it just goes to the first date thing 12:00 AM Jan 1st 1970
I fixed it thanks
When I hear this, I am really becoming a fan of twitter.
I need some help to integrate this function to my script, can you help me in some sort of way?
This is my insert code..
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$gender = $_POST['gender'];
$username = $_POST['username'];
$password = $_POST['password'];
$date = date("d/m/y - H:i");
$q = mysql_query("INSERT INTO users (firstname, lastname, gender, username, password, date) VALUES ('$firstname', '$lastname', '$gender', '$username', '$password', '$date')")
or die (mysql_error());
header("location:test2.php");
Okay, I found out..
Thanks so much for this!
Glad you found it out, but be sure to sanitize any user input!
Hmm seems like i still got some problems..
When i post i sets in “now” into the database, but it doesnt update, it just says now all the time. :-/
And when I change my date row in my table to timestamp it just says 0000-00-00 00:00:00…
You know whats wrong?
Yeah i know i have to sanitize the inputs, but its a quick code for a test to this function..
Someone please help me out here? It’s just not that easy it seems.
I’m very sorry if I posted so much. But, oh dear, after such long time I finally worked it out.
Anyway, thanks a lot for this very usefull script.
Awesome!
But how come it doesn’t count the days and the hours right? Here in Denmark the timezone is different from you. Here it’s d/m/y H:i:s
Could use some help here.
I think, it would be appreciated if you could explain how to implement this properly. Because I really see that it’s a pain in the a** if you don’t really know how to call the function correctly. And the time inserted and selected from the database.
I would love to use this function, but it seems to me that the days and hours is totally wrong, well for me it is.
Help would be appreciated
Well apparently this is not a site which answers people’s questions very good huh.
Don’t post something like this is in the future if you can’t even help people out here.
Please be patient, I don’t mind helping, but I have a lot of things going on right now that take up a lot of my time.
This is just a function to display/return a string that contains the relative time to the current time. It does nothing such as inserting data into a database.
You would just include the function code and then call the function <?php relativeTime(‘TIME’); ?>.
You might be having problems because PHP’s strtotime doesn’t understand the string you’re passing in (it thinks the format is m/d/y). Sorry!
A very useful script
I guess i’ll include it in every site from now on
added new knowledge! thanks mate!