How to convert decimal hour value to hh:mm:ss

前端 未结 2 1533
无人共我
无人共我 2021-01-01 20:29

How can I convert a decimal hour value like 1.6578 to hh:mm:ss in jquery or javascript?

I only managed to do it to hh:mm using this code:

var decimal         


        
相关标签:
2条回答
  • 2021-01-01 20:38

    You could do something like this:

    var decimalTimeString = "1.6578";
    var decimalTime = parseFloat(decimalTimeString);
    decimalTime = decimalTime * 60 * 60;
    var hours = Math.floor((decimalTime / (60 * 60)));
    decimalTime = decimalTime - (hours * 60 * 60);
    var minutes = Math.floor((decimalTime / 60));
    decimalTime = decimalTime - (minutes * 60);
    var seconds = Math.round(decimalTime);
    if(hours < 10)
    {
    	hours = "0" + hours;
    }
    if(minutes < 10)
    {
    	minutes = "0" + minutes;
    }
    if(seconds < 10)
    {
    	seconds = "0" + seconds;
    }
    alert("" + hours + ":" + minutes + ":" + seconds);

    0 讨论(0)
  • 2021-01-01 20:53

    Rather than doing the calculations yourself, use built-in functionality to set the seconds on an arbitrary date of a Date object, convert it to a string, and chop off the date part, leaving just the hh:mm:ss string.

    var decimalTimeString = "1.6578";
    var n = new Date(0,0);
    n.setSeconds(+decimalTimeString * 60 * 60);
    document.write(n.toTimeString().slice(0, 8));

    0 讨论(0)
提交回复
热议问题