# Javascript Time Calculation

I'm building a JavaScript function that will calculate the hours between two times. time format is military time.

the below code should output `2.25`. instead it outputs `2.75`.

Any Ideas what I've done wrong, or what I'm missing.
``````<script type="text/javascript" language="javascript">
function calcHours(timein,timeout){
var timeIn = timein.split(':');
var timeOut = timeout.split(':');
var timeInF = parseInt(timeIn[1])
var timeOutF = parseInt(timeOut[1]);
var minIn = timeInF / 60;
var minOut = timeOutF / 60;
var totalMin = minIn + minOut;
var hourIn = parseInt(timeIn[0]);
var hourOut = parseInt(timeOut[0]);
if(hourIn < hourOut){
var totalHours = hourOut - hourIn;
}
if(hourIn > hourOut){
var totalHours = 24 - hourIn;
totalHours = totalHours + hourOut;
}
totalHours = totalHours + totalMin;
}

calcHours('6:15','8:30');

</script>
``````
LVL 2
###### Who is Participating?

Commented:
Oops, wrong again.  It calcs milliseconds, so divide by 3600000.

function calcHours(timein,timeout) {
var date1 = new Date('1/1/2009 ' + timein);
var date2 = new Date('1/1/2009 ' + timeout);
var sec = (date2.getTime() - date1.getTime()) \ 3600000;
}
0

Commented:
line 9 should be
var totalMin = minOut - minIn;

Thanks
Ajitha
0

Commented:
change:
var totalMin =  minIn+minOut ;

to:
var totalMin =  minOut-minIn ;
0

Commented:
Why all the math?  Why not just use Date class like this:

function calcHours(timein,timeout) {
var date1 = new Date('1/1/2009 ' + timein);
var date2 = new Date('1/1/2009 ' + timeout);
var sec = date2.getTime() - date1.getTime();
}
0

Commented:
Sorry.  Function above calculates seconds.  For hours, just divide by 3600.
0

Author Commented:
Perfect!
0

Author Commented:
alright Bill...

lets say time in is '23:15' and and time out is 3:30.

how would i get that to output the correct number of hours?

``````calcHours('23:15','3:30');
``````
0

Author Commented:
0

Commented:
Well, it depends on what you consider 'correct'.

Should the code assume that the second time is for the next day and return 4.25?  If so, how do we know that the second time is not 2 or 3 days away?  If the times can span multiple days, you really need to pass the date into the function.  If we can assume that the second date always follows the first date and is no more than 1 day away, we can handle that with a couple of lines of extra code.

Should the code just return the difference (-19.75)?  (probably not, since that is what it does now).

Should the code return the absolute value of the difference (19.75).  (this is easy enough).

0

Commented:
>> RE: Any good with PHP?

No, but if there's a Date object available, you should use it.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.