我想转换时间的持续时间,即秒数,以冒号分隔的时间字符串(hh:mm:ss)

我在这里找到了一些有用的答案,但它们都谈到了转换成x小时和x分钟的格式。

那么有一个小片段,这是在jQuery或只是原始JavaScript?


当前回答

function formatTime(seconds) {
    return [
        parseInt(seconds / 60 / 60),
        parseInt(seconds / 60 % 60),
        parseInt(seconds % 60)
    ]
        .join(":")
        .replace(/\b(\d)\b/g, "0$1")
}

其他回答

可以使用以下函数将时间转换为HH:MM:SS格式:

var convertTime = function (input, separator) {
    var pad = function(input) {return input < 10 ? "0" + input : input;};
    return [
        pad(Math.floor(input / 3600)),
        pad(Math.floor(input % 3600 / 60)),
        pad(Math.floor(input % 60)),
    ].join(typeof separator !== 'undefined' ?  separator : ':' );
}

在不传递分隔符的情况下,它使用:作为(默认)分隔符:

time = convertTime(13551.9941351); // --> OUTPUT = 03:45:51

如果你想使用-作为分隔符,只需将其作为第二个参数传递:

time = convertTime(1126.5135155, '-'); // --> OUTPUT = 00-18-46

Demo

var convertTime = function (input, separator) { var pad = function(input) {return input < 10 ? "0" + input : input;}; return [ pad(Math.floor(input / 3600)), pad(Math.floor(input % 3600 / 60)), pad(Math.floor(input % 60)), ].join(typeof separator !== 'undefined' ? separator : ':' ); } document.body.innerHTML = '<pre>' + JSON.stringify({ 5.3515555 : convertTime(5.3515555), 126.2344452 : convertTime(126.2344452, '-'), 1156.1535548 : convertTime(1156.1535548, '.'), 9178.1351559 : convertTime(9178.1351559, ':'), 13555.3515135 : convertTime(13555.3515135, ',') }, null, '\t') + '</pre>';

看看这小提琴。

以下是我的解决方案。您可以尝试下面的代码片段。

函数secToHHMM(sec) { var d = new Date(); d.setHours (0); d.setMinutes (0); d.setSeconds (0); d = new Date(d.getTime() + sec*1000); 返回d.toLocaleString (en)。分割(' ')[1]; }; alert('One hour: ' + secToHHMM(60*60));/ /“01:00:00” alert(' 1小时5分钟:' + secToHHMM(60*60 + 5*60));/ /“01:05:00” alert(' 1小时5分23秒:' + secToHHMM(60*60 + 5*60 + 23));/ /“01:05:23”

以下是@meiyang的优秀解决方案的一个变体,我最终使用了它:

    function duration(seconds) {
        return [
            format(seconds / 60 / 60),
            format(seconds / 60 % 60),
            format(seconds % 60)
        ].join(':');
    }

    format(n) {
        return (~~n).toString().padStart(2, '0')
    }

PS:同样值得注意的是,上面的一些其他解决方案只适用于< 24h的值

const secondsToTime = (seconds, locale) => { const date = new date (0); 日期。setHours(0, 0, seconds, 0); 返回date.toLocaleTimeString(地区); } “en”console.log (secondsToTime (3610));

在哪里区域参数(“en”,“de”等)是可选的

我是这么做的

function timeFromSecs(seconds)
{
    return(
    Math.floor(seconds/86400)+'d :'+
    Math.floor(((seconds/86400)%1)*24)+'h : '+
    Math.floor(((seconds/3600)%1)*60)+'m : '+
    Math.round(((seconds/60)%1)*60)+'s');
}

timeFromSecs(22341938)将返回“258d 14h 5m 38s”