Craig Francis


PHP Human Time

If you have a number of seconds, and you want to show it in a human readable format, then you can use this function...

function unix2human($unix) {

//--------------------------------------------------
// Maths

$sec = $unix % 60;
$unix -= $sec;

$minSeconds = $unix % 3600;
$unix -= $minSeconds;
$min = ($minSeconds / 60);

$hourSeconds = $unix % 86400;
$unix -= $hourSeconds;
$hour = ($hourSeconds / 3600);

$daySeconds = $unix % 604800;
$unix -= $daySeconds;
$day = ($daySeconds / 86400);

$week = ($unix / 604800);

//--------------------------------------------------
// Text

$output = '';

if ($week > 0) $output .= ', ' . $week . ' week' . ($week != 1 ? 's' : '');
if ($day > 0) $output .= ', ' . $day . ' day' . ($day != 1 ? 's' : '');
if ($hour > 0) $output .= ', ' . $hour . ' hour' . ($hour != 1 ? 's' : '');
if ($min > 0) $output .= ', ' . $min . ' minute' . ($min != 1 ? 's' : '');

if ($sec > 0 || $output == '') {
$output .= ', ' . $sec . ' second' . ($sec != 1 ? 's' : '');
}

//--------------------------------------------------
// Grammar

$output = substr($output, 2);
$output = preg_replace('/, ([^,]+)$/', ' and $1', $output);

//--------------------------------------------------
// Return the output

return $output;

}

And for an example of its usage...

echo unix2human(30);
// OUTPUT: 30 seconds

echo unix2human(183);
// OUTPUT: 3 minutes and 3 seconds

echo unix2human(237905);
// OUTPUT: 2 days, 18 hours, 5 minutes and 5 seconds

echo unix2human(strtotime('18:00') - strtotime('16:20'));
// OUTPUT: 1 hour and 40 minutes

This can be useful if you have two UNIX time-stamps and want to show the difference between the two dates.

Any feedback would be greatly appreciated. If you would like to use this code, please read the licence it is released under.