How to convert a decimal into time, eg. HH:MM:SS

前端 未结 5 1053
栀梦
栀梦 2020-12-09 12:01

I am trying to take a decimal and convert it so that I can echo it as hours, minutes, and seconds.

I have the hours and minutes, but am breaking my brain trying to f

5条回答
  •  遥遥无期
    2020-12-09 12:26

    If $dec is in hours ($dec since the asker specifically mentioned a decimal):

    function convertTime($dec)
    {
        // start by converting to seconds
        $seconds = ($dec * 3600);
        // we're given hours, so let's get those the easy way
        $hours = floor($dec);
        // since we've "calculated" hours, let's remove them from the seconds variable
        $seconds -= $hours * 3600;
        // calculate minutes left
        $minutes = floor($seconds / 60);
        // remove those from seconds as well
        $seconds -= $minutes * 60;
        // return the time formatted HH:MM:SS
        return lz($hours).":".lz($minutes).":".lz($seconds);
    }
    
    // lz = leading zero
    function lz($num)
    {
        return (strlen($num) < 2) ? "0{$num}" : $num;
    }
    

提交回复
热议问题