PHP: Printing time differences nicely, or prettytime()

One of the primary internal functional changes to Rollator, besides becoming a CMS unto it’s own right – from it’s old blog days, is to tout full administrative functionality; with not only a localized ‘root’, or ‘Administration’ user, but to offer subusers various access to editing and modifications, et al.

After re-implementing my cookie logic to use PHP sessions instead, I figured I might do a bit of cleanup of the backend interface; it’s quite usable, as you can see in this elder version, but lacks a bit of refining polish.

One of the simple changes rolled into my existing system uses quite a bit of my initally-planned functionale. This is the ability to understand idling users; or people who login and neglect to post, or logout of the interface for a specific amount of time. Heck, we’ve all done it.

After implementing my idlecheck system, I figured it’d be much more logical and easier on the mind to give the user feedback as to various aspects of this. One of these features is my Administrative Toolbar, present atop of every internal functionale; it provides information as to what has occured, based upon what the user has entered.

One of these is, ta-da the display of this idle time. It’s quite trivial, and fairly unnecessary, as Rollator will, in plain english, tell the user if it logs them out, and why.

This data is stored as a numeric, which is the offset since the last point of activity, and the current time. I store this as a number of seconds, both for the ‘idle since’ numeric, and the ‘overall time’. Getting deeper into this logic is beyond the scope of this article.

However, I created a simple function I call prettytime() which will take an argument as a number of seconds, and convert it to a number of minutes and seconds, outputting this as a rather legable, human friendly string.

It’s a bit tight, and not horribly commented, but quite easy to get the gist of:

function prettytime($time) { // Returns an arbitrary pretty date of minutes and seconds, // assumes strings are in seconds. if (is_numeric($time)) { // Let’s get this messy math out of the way $minutes = floor(round(($time / 60) , 2)); $seconds = $time – ($minutes * 60); $string = ($minutes != “0”) ? ”$minutes minute” : “”; $string .= ($minutes > “1”) ? “s” : “”; if ($minutes != “0” && $seconds != “0”) $string .= ”, ”; $string .= ($seconds != “0”) ? ”$seconds second” : “”; $string .= ($seconds > “1”) ? “s” : “”; return $string; } }

It’s pretty simple in nature, and there’s just a few things I’ve done to make it nicer. If either of these (second, minute) are above 1, it will append an ’s’, so you will get data such as 2 minutes, 1 second, and 14 seconds, respectively.

Hope it helps you out.