Skip to main content

Convert number of seconds to human readable string.

<?php

/**
 * Convert number of seconds to human readable string
 *
 * If you need to time how log a script takes to run or part of it,
 * this function is a life saver.
 *
 * @link https://mebsd.com/category/coding-snipits/php-code-snipits/page/2
 * @param number $duration
 * @return mixed|string
 */
function secs_to_str ($duration)
{
    $periods = array(
        'day' => 86400,
        'hour' => 3600,
        'minute' => 60,
        'second' => 1
    );

    $parts = array();

    foreach ($periods as $name => $dur) {
        $div = floor($duration / $dur);

        if ($div == 0)
            continue;
        else
            if ($div == 1)
                $parts[] = $div . " " . $name;
            else
                $parts[] = $div . " " . $name . "s";
        $duration %= $dur;
    }

    $last = array_pop($parts);

    if (empty($parts))
        return $last;
    else
        return join(', ', $parts) . " and " . $last;
}

// -----------------------------------------------
// EXAMPLE USAGE:
// -----------------------------------------------

$start_time = time();

// put your code here
sleep(rand(1, 10)); // to give us some test data

$stop_time = time();
$seconds_taken = $stop_time - $start_time;

print(secs_to_str($seconds_taken));
// 9 seconds
// 2 hours, 8 minutes and 55 seconds
// 1 day, 10 hours, 30 minutes and 19 seconds

?>