Basically this script will subtract StartTime from EndTime, using a jQuery plugin the html form is populated with Start and End Time in the format HH:MM, an input field is populated with the result, it works except for one issue:
If Start Time is between 08:00 and 09:59 it just returns strange results - results are 10 hours off to be precise, why?
All other inputs calculate properly!
function setValue() {
var startTime = document.getElementById('ToilA');
var endTime = document.getElementById('EndHours'); startTime = startTime.value.split(":");
var startHour = parseInt(startTime[0]);
var startMinutes = parseInt(startTime[1]);
endTime = endTime.value.split(":");
var endHour = parseInt(endTime[0]);
var endMinutes = parseInt(endTime[1]);
//var hours, minutes;
var today = new Date();
var time1 = new Date(2000, 01, 01, startHour, startMinutes, 0);
var time2 = new Date(2000, 01, 01, endHour, endMinutes, 0); var milliSecs = (time2 - time1);
msSecs = (1000);
msMins = (msSecs * 60);
msHours = (msMins * 60);
numHours = Math.floor(milliSecs/msHours);
numMins = Math.floor((milliSecs - (numHours * msHours)) / msMins);
numSecs = Math.floor((milliSecs - (numHours * msHours) - (numMins * msMins))/ msSecs); numSecs = "0" + numSecs; numMins = "0" + numMins; DateCalc = (numHours + ":" + numMins);
document.getElementById('CalculateHours').value = DateCalc; }
Whenever you have math problems with the number 8, it's something getting converted into the octal system :)
Numbers starting with 0
are interpreted as octal numbers in Javascript.
It's no problem from 01..07
, because they are the same in both systems.
But 08
and 09
don't exist in the system, so they return 0
.
Also see this question that also provides a solution: Specify the base parameter when doing the parseInt:
parseInt("09", 10); // base 10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With