Jquery time difference in hours from two fields

try

var diff = ( new Date("1970-1-1 " + end_time) - new Date("1970-1-1 " + start_time) ) / 1000 / 60 / 60;  

have a fiddle


   var start = '5:30';
   var end = '7:50';
   s = start.split(':');
   e = end.split(':');
   min = e[1]-s[1];
   hour_carry = 0;
   if(min < 0){
       min += 60;
       hour_carry += 1;
   }
   hour = e[0]-s[0]-hour_carry;
   min = ((min/60)*100).toString()
   diff = hour + ":" + min.substring(0,2);
   alert(diff);

It depends on what format you want your output in. When doing math with Date objects, it converts them into milliseconds since Epoch time (January 1, 1970, 00:00:00 UTC). By subtracting the two (and taking absolute value if you don't know which is greater) you get the raw number of milliseconds between the two.

From there, you can convert it into whatever format you want. To get the number of seconds, just divide that number by 1000. To get hours, minutes, and seconds:

var diff =  Math.abs(new Date(end_time) - new Date(start_time));
var seconds = Math.floor(diff/1000); //ignore any left over units smaller than a second
var minutes = Math.floor(seconds/60); 
seconds = seconds % 60;
var hours = Math.floor(minutes/60);
minutes = minutes % 60;

alert("Diff = " + hours + ":" + minutes + ":" + seconds);

You could of course make this smarter with some conditionals, but this is just to show you that using math you can format it in whatever form you want. Just keep in mind that a Date object always has a date, not just a time, so you can store this in a Date object but if it is greater than 24 hours you will end up with information not really representing a "distance" between the two.


try this :

var diff = new Date("Aug 08 2012 9:30") - new Date("Aug 08 2012 5:30");
diff_time = diff/(60*60*1000);