Give Your Visitors a Relative Time

Toby Somerville recently blogged about giving visitors a rough time – instead of displaying exact timestamps, providing a rough written approximation of the time.

Toby suggested that we generally communicate in approximate times, but on the web we usually work with exact timestamps. His idea was that by displaying the time as you would describe it verbally, he could better communicate the time in a visitor-friendly way.

After reading his post, I understood the merits of the approach, but it struck me that a relative time might be a little more useful for many situations. For example, in a fast moving discussion, a short timestamp (e.g. 8:30 AM) as well as a verbal summary of how long ago the time was (e.g. “4 hours ago”, “20 minutes ago”) are most useful to the user. In fact, this is precisely what Gmail does:

A common feature of Gmail’s timestamp system is approximation, similar to what Toby was getting at. For example, as you approach 60 minutes in the hour, Gmail seems to switch from “x minutes ago” to “1 hour ago”, even if you’re not quite there.

Now, I figured this could be achieved very easily in PHP – and it could. After the jump, here’s the code:

It's got a few unusual constants in there - the number values refer to 75% of the number of seconds in a particular period of time. 75% seemed like a reasonable measure beyond which we could round up - for example, the function will say "45 seconds ago" for 45 seconds, but "1 minute ago" for 46. The same goes for 2700 seconds, equal to 45 minutes, and 64800 seconds, or eighteen hours. Beyond this it simply uses the number of days.

So give it a go - it's especially handy for message boards, comment lists and news readers, especially with threaded discussion. The code is very basic at the moment, suitable for adapting to whatever purpose you see fit.