I found the following code which is working well for a time sheet calculator I am using
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));
It works fine when time1 is greater than time2, if time1 is less than time2 an extra hour is subtracted eg.
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"
I think its something to do with the Math.floor in the convertHours function.
I am trying to build something that can just take hours and minutes and subtract/add time, not actually times just quantities of hours and minutes.
There must be a simpler way that sadly eludes me, any help would be greatly appreciated.
Floor works different than most people expect for negative numbers. It returns the next integer less than the operand, so for -1.5 it will return -2. The easiest way to deal with this is just to take the absolute value (
Math.abs) then add the negative sign back at the end.