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

2020-02-04 20:57发布

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 find the seconds. Been googling for awhile with no luck. I'm sure it is quite simple, but nothing I have tried has worked. Any advice is appreciated!

Here is what I have:

function convertTime($dec)
{
    $hour = floor($dec);
    $min = round(60*($dec - $hour));
}

Like I said, I get the hour and minute without issue. Just struggling to get seconds for some reason.

Thanks!

标签: php
5条回答
ゆ 、 Hurt°
2楼-- · 2020-02-04 21:08

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;
}
查看更多
做个烂人
3楼-- · 2020-02-04 21:09

Everything upvoted didnt work in my case. I have used that solution to convert decimal hours and minutes to normal time format. i.e.

function clockalize($in){

    $h = intval($in);
    $m = round((((($in - $h) / 100.0) * 60.0) * 100), 0);
    if ($m == 60)
    {
        $h++;
        $m = 0;
    }
    $retval = sprintf("%02d:%02d", $h, $m);
    return $retval;
}


clockalize("17.5"); // 17:30
查看更多
▲ chillily
4楼-- · 2020-02-04 21:20

I am not sure if this is the best way to do this, but

$variabletocutcomputation = 60 * ($dec - $hour);
$min = round($variabletocutcomputation);
$sec = round((60*($variabletocutcomputation - $min)));
查看更多
你好瞎i
5楼-- · 2020-02-04 21:21

Very simple solution in one line:

echo gmdate('H:i:s', floor(5.67891234 * 3600));
查看更多
Ridiculous、
6楼-- · 2020-02-04 21:24

This is a great way and avoids problems with floating point precision:

function convertTime($h) {
    return [floor($h), (floor($h * 60) % 60), floor($h * 3600) % 60];
}
查看更多
登录 后发表回答