Search code examples
phptimeconvertersnotationnegative-number

Converting negative milliseconds into human readable format in PHP


Ok, so I have this function:

function convertTime($ms){

    $sec = floor($ms/1000);
    $ms = $ms % 1000;

    $min = floor($sec/60);
    $sec = $sec % 60;
    $t = $sec;

    $hr = floor($min/60);
    $min = $min % 60;
    $t = $min;

    $day = floor($hr/60);
    $hr = $hr % 60;
    $t = $hr . " h " . $t . " m";

    return $t;
}

It converts milliseconds into h:m and it works great with positive numbers. Example:

echo convertTime(60000);       // outputs: 0 h 1 m
echo convertTime(60000*70);    // outputs: 1 h 10 m
echo convertTime(60000*60*48); // outputs: 48 h 0 m

(I dont want it to convert to days so its great that it shows the actual number of hours) Unfortunately, it doesnt work very well with negative numbers...

echo convertTime(-60000);    //outputs: -1 h -1 m (should be 0 h -1 m)

Any ideas on how to compensate for this?


Solution

  • Here is your original function, formatted, unnecessary lines removed and three lines added:

    function convertTime($ms)
    {
        $sign = $ms < 0 ? "-" : "";
        $ms = abs($ms);
        $sec = floor($ms / 1000);
        $ms = $ms % 1000;
        $min = floor($sec / 60);
        $sec = $sec % 60;
        $hr = floor($min / 60);
        $min = $min % 60;
        $day = floor($hr / 60);
        $hr = $hr % 60;
        return "$sign$hr h $min m";
    }
    echo convertTime(+60000);      //  0 h 1 m
    echo convertTime(-60000);      // -0 h 1 m
    echo convertTime(-60000 * 60); // -1 h 0 m
    

    Here is my version of the same function:

    function convertTime($ms)
    {
        $xx = $ms < 0 ? "-" : "+";
        $ms = abs($ms);
        $ss = floor($ms / 1000);
        $ms = $ms % 1000;
        $mm = floor($ss / 60);
        $ss = $ss % 60;
        $hh = floor($mm / 60);
        $mm = $mm % 60;
        $dd = floor($hh / 24);
        $hh = $hh % 24;
        return sprintf("%s%dd %02dh %02dm %02d.%04ds", $xx, $dd, $hh, $mm, $ss, $ms);
    }