如何将小数转换为时间,例如。 HH:MM:SS

时间:2012-02-01 20:19:15

标签: php

我正在尝试取一个小数并将其转换为我可以将其作为小时,分钟和秒来回显。

我有时间和分钟,但我正在试图找到秒钟。谷歌搜索了一段时间没有运气。我确信这很简单,但我尝试过的任何工作都没有。任何建议表示赞赏!

这就是我所拥有的:

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

就像我说的那样,我得到的时间和分钟没有问题。由于某种原因,只是努力争取秒数。

谢谢!

5 个答案:

答案 0 :(得分:21)

如果$dec以小时为单位($dec,因为提问者明确提到 dec imal):

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;
}

答案 1 :(得分:9)

一行中非常简单的解决方案:

echo gmdate('H:i:s', floor(5.67891234 * 3600));

答案 2 :(得分:3)

所有上调的东西都不适用于我的情况。 我使用该解决方案将十进制小时和分钟转换为正常时间格式。 即

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

答案 3 :(得分:0)

我不确定这是否是最好的方法,但是

$variabletocutcomputation = 60 * ($dec - $hour);
$min = round($variabletocutcomputation);
$sec = round((60*($variabletocutcomputation - $min)));

答案 4 :(得分:0)

这是一种很好的方法,可以避免浮点精度问题:

function convertTime($h) {
    return [floor($h), (floor($h * 60) % 60), floor($h * 3600) % 60];
}