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

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

    I like the first answer. There some optimisations:

    • source data is a Number. additional calculations is not needed.

    • much excess computing

    Result code:

    Number.prototype.toHHMMSS = function () {
        var seconds = Math.floor(this),
            hours = Math.floor(seconds / 3600);
        seconds -= hours*3600;
        var minutes = Math.floor(seconds / 60);
        seconds -= minutes*60;
    
        if (hours   < 10) {hours   = "0"+hours;}
        if (minutes < 10) {minutes = "0"+minutes;}
        if (seconds < 10) {seconds = "0"+seconds;}
        return hours+':'+minutes+':'+seconds;
    }
    

提交回复
热议问题