views:

57

answers:

1

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; }
+9  A: 

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
Unicron
When a number begins with a zero, the ECMAScript standard allows an implementation of parseInt() to interpret it as an octal number or a decimal number, so this may work on one browser or not on another. To fix it for all, use "parseInt(startTime[0],10)" which forces base 10.
Mark Lutton
Thanks guys, for the answer and explanation.
I have one more issue with this code, there is a leading 0 when the minute part is over 10, so it returns something like 11:013 rather that 11:13, can this be fixed with math or will an if statement fix this? Like if number of items > 2, remove first item?I was going to just do a PHP script to remove this when the form is submitted, but it doesn't look good for the user.
@user there may be a sneaky clever way to do this more elegantly, but an `if` statement will do the job as well.
Unicron