php 如何将小数转换为时间,例如。时:分:秒

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9102680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:10:09  来源:igfitidea点击:

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

php

提问by HMFlol

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!

谢谢!

回答by Crontab

If $decis in hours ($decsince the asker specifically mentioned a decimal):

如果$dec以小时为单位($dec因为提问者特别提到了十进制):

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

回答by Cheery

Very simple solution in one line:

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

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

回答by Patrick Jaja

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

在我的情况下,所有upvoted都不起作用。我已经使用该解决方案将十进制小时和分钟转换为正常时间格式。IE

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

回答by Teldan

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

回答by Justin Pihony

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