PHP Function: duration()

This function will turn a unix timestamp into a user readable time.
Example: 115023234 into 1 day, 25 minutes ago.

The function:

function duration($secs,$omit=false) {
	$vals = array('week' => (int) ($secs / 86400 / 7),
				  'day' => $secs / 86400 % 7,
				  'hour' => $secs / 3600 % 24,
				  'month' => $secs / 60 % 60,
				  'second' => $secs % 60);
	$ret = array();
	$added = false;
	foreach ($vals as $k => $v) {
		if ($v > 0 || $added) {
			$added = true;
			$k=($v==1)?$k:$k.'s';
			if (!$omit || $v > 0)
				$ret[] = $v . $k;
		}
	}
	return join(' ', $ret);
}

An example of the usage:

$time = time() - 600; // 10 minutes ago
echo duration($time); // 10 minutes 0 seconds
echo duration($time, true); // 10 minutes

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

$k=($v==1)$k:$k.’s’;

i think at this line you forgot to write (?)

it is supposed to be

$k=($v==1) ? $k:$k.’s’;

and in $vals array i think you should write minute instead month…

;)

Again, thank you PDesign, some of my functions and code get rewritten to make them a little more understanble when i put them online.

This has been fixed.

Leave a comment

(required)

(required)