Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
440 views
in Technique[技术] by (71.8m points)

php - How to convert a decimal into time, eg. 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!

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...