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

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

    Here's how I did it. It seems to work fairly well, and it's extremely compact. (It uses a lot of ternary operators, though)

    function formatTime(seconds) {
      var hh = Math.floor(seconds / 3600),
        mm = Math.floor(seconds / 60) % 60,
        ss = Math.floor(seconds) % 60;
      return (hh ? (hh < 10 ? "0" : "") + hh + ":" : "") + ((mm < 10) && hh ? "0" : "") + mm + ":" + (ss < 10 ? "0" : "") + ss
    }
    

    ...and for formatting strings...

    String.prototype.toHHMMSS = function() {
      formatTime(parseInt(this, 10))
    };
    

提交回复
热议问题