将秒转换为HH:mm:ss?

时间:2016-08-16 05:26:37

标签: javascript jquery node.js time momentjs

当我尝试将秒数转换为hh:mm:ss格式时,我的时间超过两个字符。

var seconds = 4287050531;
var getTime = formatTime(seconds);
console.log("Time Is :"+getTime);// 1190847:22:11 

function formatTime(seconds) {
  return [pad(Math.floor(seconds/3600)),
          pad(Math.floor(seconds/60)%60),
          pad(seconds%60),
          ].join(":");
}

function pad(num) {
  if(num < 10) {
    return "0" + num;
  } else {
    return "" + num;
  }
}

3 个答案:

答案 0 :(得分:1)

请试试以下功能:

 function convert(seconds) {
    seconds = Number(seconds);
    var hours = Math.floor(seconds / 3600);
    var minutes = Math.floor(seconds % 3600 / 60);
    var seconds = Math.floor(seconds % 3600 % 60);
    return ((hours > 0 ? hours + ":" + (minutes < 10 ? "0" : "") : "") + minutes + ":" + (seconds < 10 ? "0" : "") +`enter code here` seconds); 
}

答案 1 :(得分:0)

为什么不使用moment-duration-format模块

npm install moment-duration-format

var moment = require("moment-duration-format");

moment.duration(seconds, "seconds").format("h:m:s");

https://github.com/jsmreese/moment-duration-format

答案 2 :(得分:-1)

尝试使用datejs

使用它可以轻松转换它

(new Date).clearTime()
          .addSeconds(4287050531)
          .toString('H:mm:ss');