我发现以下代码适用于我正在使用的时间表计算器
function convertSecondsToHHMMSS(intSecondsToConvert) {
var hours = convertHours(intSecondsToConvert);
var minutes = getRemainingMinutes(intSecondsToConvert);
minutes = (minutes == 60) ? "00" : minutes;
var seconds = getRemainingSeconds(intSecondsToConvert);
return hours+" hrs "+minutes+" mins";
}
function convertHours(intSeconds) {
var minutes = convertMinutes(intSeconds);
var hours = Math.floor(minutes/60);
return hours;
}
function convertMinutes(intSeconds) {
return Math.floor(intSeconds/60);
}
function getRemainingSeconds(intTotalSeconds) {
return (intTotalSeconds%60);
}
function getRemainingMinutes(intSeconds) {
var intTotalMinutes = convertMinutes(intSeconds);
return (intTotalMinutes%60);
}
function HMStoSec1(T) {
var A = T.split(/\D+/) ; return (A[0]*60 + +A[1])*60 + +A[2]
}
var time1 = HMStoSec1("10:00:00");
var time2 = HMStoSec1("12:05:00");
var diff = time2 - time1;
document.write(convertSecondsToHHMMSS(diff));
当time1大于time2时,它工作正常,如果time1小于time2,则减去额外的小时,例如。
var time1 = HMStoSec1("09:00:00");
var time2 = HMStoSec1("08:55:00");
var diff = time2 - time1;
document.write(convertSecondsToHHMMSS(diff)); // writes "1 hr 5 mins" instead of "0 hr 5 mins"
我认为它与convertHours函数中的Math.floor有关。
我正在尝试构建一些可能需要花费数小时和数分钟并减去/添加时间的东西,而不是实际上只是小时和分钟的数量。
必须有一种更简单的方式让我难过,任何帮助都会受到高度赞赏。
答案 0 :(得分:2)
楼层的工作方式与大多数人对负数的预期不同。它返回小于操作数的下一个整数,因此对于-1.5,它将返回-2。解决这个问题最简单的方法就是取绝对值(Math.abs
),然后在最后添加负号。