无法将秒转换为HH:MM:SS

时间:2015-03-20 17:28:40

标签: javascript

尝试将秒转换为HH:MM:SS秒格式时,我得到的结果不正确。例如,如果seconds的值为289,则会议记录为0。这可能是什么原因

var seconds = this.currentTime;
var hours = Math.floor(seconds/3600); // Get whole hours
seconds -= hours*3600;

var minutes = Math.floor(seconds/3600); // Get remaining minutes
console.log("minutes : " + minutes);
seconds -= minutes*60;

var timeNow = hours + ":" + (minutes<10 ? '0'+minutes : minutes) + ":" + (seconds<10 ? '0'+seconds : seconds);

2 个答案:

答案 0 :(得分:3)

要计算分钟数,你应该将秒数除以60而不是3600(毕竟一分钟内有60秒):

var minutes = Math.floor(seconds/60); // Get remaining minutes

您还可以使用JavaScript中的Date对象为您完成大部分操作:

var date = new Date(0, 0, 0, 0, 0, 289, 0);
var minutes = date.getMinutes();
// etc.

答案 1 :(得分:1)

var timeInSec = this.currentTime;
var hours = Math.floor(timeInSec / 3600) % 24; // Get whole hours
var minutes = Math.floor(timeInSec / 60) % 60; // Get remaining minutes
var seconds = timeInSec % 60; // Get remaining seconds
var timeNow = (hours < 10 ? "0" + hours : hours) + "-" + (minutes < 10 ? "0" + minutes : minutes) + "-" + (seconds  < 10 ? "0" + seconds : seconds);