如何使用JavaScript将秒转换为HH-MM-SS字符串?


当前回答

有很多解决这个问题的选项,显然有很好的选项建议,但我想在这里添加一个更优化的代码

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(":");
}

如果你不想格式化0和小于10的数字,你可以使用

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

}

示例代码http://fiddly.org/1c476/1

其他回答

正如Cleiton在他的回答中指出的,moment.js可以用于:

moment().startOf('day')
        .seconds(15457)
        .format('H:mm:ss');

我只是想对上面这个不错的答案做一点解释:

var totalSec = new Date().getTime() / 1000;
var hours = parseInt( totalSec / 3600 ) % 24;
var minutes = parseInt( totalSec / 60 ) % 60;
var seconds = totalSec % 60;

var result = (hours < 10 ? "0" + hours : hours) + "-" + (minutes < 10 ? "0" + minutes : minutes) + "-" + (seconds  < 10 ? "0" + seconds : seconds);

On the second line, since there are 3600 seconds in 1 hour, we divide the total number of seconds by 3600 to get the total number of hours. We use parseInt to strip off any decimal. If totalSec was 12600 (3 and half hours), then parseInt( totalSec / 3600 ) would return 3, since we will have 3 full hours. Why do we need the % 24 in this case? If we exceed 24 hours, let's say we have 25 hours (90000 seconds), then the modulo here will take us back to 1 again, rather than returning 25. It is confining the result within a 24 hour limit, since there are 24 hours in one day.

当你看到这样的东西:

25 % 24

你可以这样想:

25 mod 24 or what is the remainder when we divide 25 by 24

您尝试过向Date对象添加秒数吗?

Date.prototype.addSeconds = function(seconds) {
    this.setSeconds(this.getSeconds() + seconds);
};
var dt = new Date();
dt.addSeconds(1234);

一个示例: https://jsfiddle.net/j5g2p0dc/5/

更新: 样本链接缺失,所以我创建了一个新的。

这招很管用:

function secondstotime(secs)
{
    var t = new Date(1970,0,1);
    t.setSeconds(secs);
    var s = t.toTimeString().substr(0,8);
    if(secs > 86399)
        s = Math.floor((t - Date.parse("1/1/70")) / 3600000) + s.substr(2);
    return s;
}

(来源此处)

当我想象一个时钟或计时器时,我会这样做:

const secondsTo_HHMMSS = (seconds) => {
      //format to a readable friendly timer
      let hour = Math.floor(seconds / 3600);
      let minute = Math.floor((seconds % 3600) / 60);
      let second = seconds % 60;

      if(hour.toString().length === 1) {
            hour = `0${hour}`;
      }
      if(minute.toString().length === 1) {
            minute = `0${minute}`;
      }
      if(second.toString().length === 1) {
            second = `0${second}`;
      };

      let timer = `${hour}-${minute}-${second}`;

      return timer;
}