Jquery time difference in hours from two fields

前端 未结 4 1436
小蘑菇
小蘑菇 2020-11-28 14:36

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.<

相关标签:
4条回答
  • 2020-11-28 15:10
       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);
    
    0 讨论(0)
  • 2020-11-28 15:15

    try

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

    have a fiddle

    0 讨论(0)
  • 2020-11-28 15:18

    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.

    0 讨论(0)
  • 2020-11-28 15:24

    try this :

    var diff = new Date("Aug 08 2012 9:30") - new Date("Aug 08 2012 5:30");
    diff_time = diff/(60*60*1000);
    
    0 讨论(0)
提交回复
热议问题