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

前端 未结 30 1766
太阳男子
太阳男子 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:33

    function toHHMMSS(seconds) {
        var h, m, s, result='';
        // HOURs
        h = Math.floor(seconds/3600);
        seconds -= h*3600;
        if(h){
            result = h<10 ? '0'+h+':' : h+':';
        }
        // MINUTEs
        m = Math.floor(seconds/60);
        seconds -= m*60;
        result += m<10 ? '0'+m+':' : m+':';
        // SECONDs
        s=seconds%60;
        result += s<10 ? '0'+s : s;
        return result;
    }
    

    Examples

        toHHMMSS(111); 
        "01:51"
    
        toHHMMSS(4444);
        "01:14:04"
    
        toHHMMSS(33);
        "00:33"
    

提交回复
热议问题