如何在jquery或javascript中将十进制小时值(如1.6578)转换为hh:mm:ss?
我只是设法用hh:mm使用这段代码:
var decimaltime= "1.6578";
var hrs = parseInt(Number(decimaltime));
var min = Math.round((Number(decimaltime)-hrs) * 60);
var clocktime = hrs+':'+min;
答案 0 :(得分:11)
不是自己进行计算,而是使用内置功能在Date对象的任意日期设置秒数,将其转换为字符串,然后切掉日期部分,只留下hh:mm:ss字符串
var decimalTimeString = "1.6578";
var n = new Date(0,0);
n.setSeconds(+decimalTimeString * 60 * 60);
document.write(n.toTimeString().slice(0, 8));
答案 1 :(得分:7)
你可以这样做:
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);
答案 2 :(得分:0)
我发现这个函数可以很好地将我的十进制秒值转换为 hh:mm:ss 的标准时间字符串
function formatDuration(seconds) {
return new Date(seconds * 1000).toISOString().substr(11, 8);
}
const secondsInDecimal = 1.6578;
formatDuration(secondsInDecimal);
// "00:00:01"
参考文献:
过程:
new Date(seconds * 1000)
返回此字符串 "Wed Dec 31 1969 19:00:01 GMT-0500 (Eastern Standard Time)"
"1970-01-01T00:00:01.657Z"
。这是从上面的 #1 返回的简化字符串。"00:00:01"
。