[英]How to convert a decimal into time, eg. HH:MM:SS
我试图取一个小数并转换它,以便我可以回答它为小时,分钟和秒。
我有时间和分钟,但我正在试图找到秒钟。 谷歌搜索了一段时间没有运气。 我确信这很简单,但我尝试过的任何工作都没有。 任何建议表示赞赏!
这是我有的:
function convertTime($dec)
{
$hour = floor($dec);
$min = round(60*($dec - $hour));
}
就像我说的那样,我得到的时间和分钟没有问题。 因某种原因只是努力争取秒数。
谢谢!
如果$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;
}
一行非常简单的解决方案:
echo gmdate('H:i:s', floor(5.67891234 * 3600));
在我的情况下,一切upvoted都没有用。 我使用该解决方案将十进制小时和分钟转换为正常时间格式。 即
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
这是一个很好的方法,可以避免浮点精度问题:
function convertTime($h) {
return [floor($h), (floor($h * 60) % 60), floor($h * 3600) % 60];
}
我不确定这是否是最好的方法,但是
$variabletocutcomputation = 60 * ($dec - $hour);
$min = round($variabletocutcomputation);
$sec = round((60*($variabletocutcomputation - $min)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.