Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange bug in this time calculation script?

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; }
like image 412
Ezugo C Avatar asked Jan 22 '23 19:01

Ezugo C


1 Answers

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
like image 52
Unicron Avatar answered Feb 01 '23 00:02

Unicron