Jquery time difference in hours from two fields

I have two fields in my form where users select an input time (start_time, end_time) I would like to, on the change of these fields, recalcuate the value for another field.

What I would like to do is get the amount of hours between 2 times. So for instance if I have a start_time of 5:30 and an end time of 7:50, I would like to put the result 2:33 into another field.

My inputted form times are in the format HH:MM:SS

So far I have tried...

$('#start_time,#end_time').on('change',function() 
{
  var start_time = $('#start_time').val();
  var end_time = $('#end_time').val();

    var diff =  new Date(end_time) - new Date( start_time);  



  $('#setup_hours').val(diff);

Answers:

Answer

try

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

have a fiddle

Answer
   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);
Answer

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.

Answer

try this :

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.