JavaScript seconds to time string with format hh:mm:ss

前端 未结 30 1872
太阳男子
太阳男子 2020-11-22 07:19

I want to convert a duration of time, i.e., number of seconds to colon-separated time string (hh:mm:ss)

I found some useful answers here but they all talk about conv

30条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 07:47

    You can use the following function to convert time (in seconds) to HH:MM:SS format :

    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 : ':' );
    }
    

    Without passing a separator, it uses : as the (default) separator :

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

    If you want to use - as a separator, just pass it as the second parameter:

    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 = '
    ' + 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') +  '
    ';

    See also this Fiddle.

提交回复
热议问题