我正在尝试计算两次之间的差异并增加结果。为此,我尝试了以下代码。
function toSeconds(time_str) {
// Extract hours, minutes and seconds
var parts = time_str.split(':');
// compute and return total seconds
return parts[0] * 3600 + // an hour has 3600 seconds
parts[1] * 60 + // a minute has 60 seconds
+
parts[2]; // seconds
}
var a = "12:00:00"
var b = "13:05:02"
var difference = Math.abs(toSeconds(a) - toSeconds(b));
// format time differnece
var result = [
Math.floor(difference / 3600), // an hour has 3600 seconds
Math.floor((difference % 3600) / 60), // a minute has 60 seconds
difference % 60
];
// 0 padding and concatation
result = result.map(function (v) {
return v < 10 ? '0' + v : v;
}).join(':');
alert(result);
假设开始时间为00:05 AM,结束时间为00:10 AM。如果我们在这两次之间进行计算,结果将是5分钟。因此,我们需要像00:05:00那样增加它们。现在开始,时间将从秒,分钟到小时增加
,但是如果给出 12小时格式来计算剩余小时数,则可以使用。是否有可能计算两次之间的差并增加结果时间。
答案 0 :(得分:1)
这是您想要的吗?我创建了一个函数,该函数使用Javascript的setInterval每1秒增加一次结果变量。您可以通过调用clearInterval(x)
function toSeconds(time_str) {
// Extract hours, minutes and seconds
var parts = time_str.split(':');
// compute and return total seconds
return parts[0] * 3600 + // an hour has 3600 seconds
parts[1] * 60 + // a minute has 60 seconds
+
parts[2]; // seconds
}
var a = "12:00:00"
var b = "13:05:02"
var difference = Math.abs(toSeconds(a) - toSeconds(b));
// format time differnece
var result = [
Math.floor(difference / 3600), // an hour has 3600 seconds
Math.floor((difference % 3600) / 60), // a minute has 60 seconds
difference % 60
];
// 0 padding and concatation
// result = result.map(function (v) {
// return v < 10 ? '0' + v : v;
// }).join(':');
console.log(result);
let x = setInterval(function() {
result[2] = result[2] + 1;
if(result[2]>=60){
result[2] = 0;
result[1] = result[1] + 1;
}
if(result[1]>=60){
result[1] = 0;
result[0] = result[0] +1
}
result[0] = result[0] === 24 ? 0 : result[0]
console.log(result.map(function (v) {
return v < 10 ? '0' + v : v;
}).join(':'))
}, 1000);