License

Creative Commons License
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 Unported License.
Valid XHTML 1.0 Strict

PHP function to convert seconds to human readable string

Written by Christian Stigen Larsen — 2008-09-23

License

Creative Commons License
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 Unported License.

A simple function to convert seconds to human readable text in PHP:

/*
 * Convert seconds to human readable text.
 *
 */
function secs_to_h($secs)
{
        $units = array(
                "week"   => 7*24*3600,
                "day"    =>   24*3600,
                "hour"   =>      3600,
                "minute" =>        60,
                "second" =>         1,
        );

	// specifically handle zero
        if ( $secs == 0 ) return "0 seconds";

        $s = "";

        foreach ( $units as $name => $divisor ) {
                if ( $quot = intval($secs / $divisor) ) {
                        $s .= "$quot $name";
                        $s .= (abs($quot) > 1 ? "s" : "") . ", ";
                        $secs -= $quot * $divisor;
                }
        }

        return substr($s, 0, -2);
}

For example

secs_to_h(1382470);

will return

2 weeks, 2 days, 1 minute, 10 seconds

I especially like the version which returns an array. It's more compact and more to the point. Unfortunately, PHP lacks all the nice functions you have in e.g. Python to make this really useful:

function secs_to_v($secs)
{
        $units = array(
                "weeks"   => 7*24*3600,
                "days"    =>   24*3600,
                "hours"   =>      3600,
                "minutes" =>        60,
                "seconds" =>         1,
        );

        foreach ( $units as &$unit ) {
		$quot  = intval($secs / $unit);
		$secs -= $quot * $unit;
		$unit  = $quot;
        }

        return $units;
}

Running

var_dump(secs_to_v(1382470));

returns

array(5) {
  ["weeks"]=>
  int(2)
  ["days"]=>
  int(2)
  ["hours"]=>
  int(0)
  ["minutes"]=>
  int(1)
  ["seconds"]=>
  int(10)
}

To pretty-print it, you could use it with implode(), array_combine() and friends, or simply wrap it in a function like

function secs_to_h($secs)
{
        $s = "";

        foreach ( secs_to_v($secs) as $k => $v ) {
                if ( $v ) $s .= $v." ".($v==1? substr($k,0,-1) : $k).", ";
        }

        return substr($s, 0, -2);
}

which would do the same as the original secs_to_h().

 

blog comments powered by Disqus