Convert seconds to HH-MM-SS with JavaScript?

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

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

30条回答
  •  没有蜡笔的小新
    2020-11-22 10:13

    There are lots of options of solve this problem, and obvious there are good option suggested about, But I wants to add one more optimized code here

    function formatSeconds(sec) {
         return [(sec / 3600), ((sec % 3600) / 60), ((sec % 3600) % 60)]
                .map(v => v < 10 ? "0" + parseInt(v) : parseInt(v))
                .filter((i, j) => i !== "00" || j > 0)
                .join(":");
    }
    

    if you don't wants formatted zero with less then 10 number, you can use

    function formatSeconds(sec) {
      return parseInt(sec / 3600) + ':' + parseInt((sec % 3600) / 60) + ':' + parseInt((sec % 3600) % 60);
    

    }

    Sample Code http://fiddly.org/1c476/1

提交回复
热议问题