Convert seconds to HH-MM-SS with JavaScript?

前端 未结 30 2621
南旧
南旧 2020-11-22 10:05

How can I convert seconds to an HH-MM-SS string using JavaScript?

30条回答
  •  星月不相逢
    2020-11-22 10:32

    I know this is kinda old, but...

    ES2015:

    var toHHMMSS = (secs) => {
        var sec_num = parseInt(secs, 10)
        var hours   = Math.floor(sec_num / 3600)
        var minutes = Math.floor(sec_num / 60) % 60
        var seconds = sec_num % 60
    
        return [hours,minutes,seconds]
            .map(v => v < 10 ? "0" + v : v)
            .filter((v,i) => v !== "00" || i > 0)
            .join(":")
    }
    

    It will output:

    toHHMMSS(129600) // 36:00:00
    toHHMMSS(13545) // 03:45:45
    toHHMMSS(180) // 03:00
    toHHMMSS(18) // 00:18
    

提交回复
热议问题