如何将小数转换为时间,例如. HH:MM:SS [英] How to convert a decimal into time, eg. HH:MM:SS

查看:351
本文介绍了如何将小数转换为时间,例如. HH:MM:SS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将小数点转换为小时,分钟和秒.

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!

这就是我所拥有的:

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.

谢谢!

推荐答案

如果$dec以小时为单位(由于提问者特别提到了 dec imal,因此为$dec):

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

这篇关于如何将小数转换为时间,例如. HH:MM:SS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆