msonsona msonsona - 1 month ago 12
PHP Question

php date formatting for time difference

I just want to output as a result of a script to be executed through CLI the time the execution of the script took.

for doing that, I set a var at the start of the script

$start_time = time();


and then at the end

date('H:i:s',time() - $start_time);


the problem is that even when the ellapsed time might be in the range of seconds or minutes, it always print that at least an hour has passed:

>>> echo date('H:i:s',1);
01:00:01
>>> echo date('H:i:s', 10);
01:00:10
>>> echo date('H:i:s',3599);
01:59:59
>>> echo date('H:i:s',3600);
02:00:00


shouldn't it display 00:XX:YY, when less than an hour has passed?
is there something I'm missing, is there a bug?

thanks for your help!

Answer

Don't use date(). When you have time() - $start_time the result is in seconds. Multiply this up if you want it in mintues etc. or use the following function to convert the seconds to Hours, Minutes and Seconds.

<?php /**
 *
 * @convert seconds to hours minutes and seconds
 *
 * @param int $seconds The number of seconds
 *
 * @return string
 *
 */
function secondsToWords($seconds) {
    /*** return value ***/
    $ret = "";

    /*** get the hours ***/
    $hours = intval(intval($seconds) / 3600);
    if($hours > 0)
    {
        $ret .= "$hours hours ";
    }
    /*** get the minutes ***/
    $minutes = bcmod((intval($seconds) / 60),60);
    if($hours > 0 || $minutes > 0)
    {
        $ret .= "$minutes minutes ";
    }

    /*** get the seconds ***/
    $seconds = bcmod(intval($seconds),60);
    $ret .= "$seconds seconds";

    return $ret;
} ?>

Example usage:

<?php
    /*** time since EPOCH ***/
    echo secondsToWords(time());
?>
Comments