简体   繁体   中英

Getting difference between two times in twenty four hour format using JavaScript

I have a dropdown with starting and ending time of tuition classes.The format of the time is in 24 hours. eg-

08:30 - 12:00
21:00 - 00:00
05:00 - 10:00

I need to get the difference between start and end time in hours. And I used the following code.

var diff = parseFloat(endTime) - parseFloat(startTime);

So if I select the time 21:00 - 00:00, this gives the output as -21. But actual value should be 3 hours.Furthermore if somebody select a time as 21:00 - 00:00 the difference should be 3 hours while if somebody select a time of 21:00 - 12:00 the difference should be 15 hours. How can I achieve this ?

First solution : Convert your hour in DateTime format and use

function diff_hours(dt2, dt1) 
 {

  var diff =(dt2.getTime() - dt1.getTime()) / 1000;
  diff /= (60 * 60);
  return Math.abs(Math.round(diff));

 }

This will give you the diff in hours.

Second solution : custom function if you really want to use only string.

function diffTime(time1,time2) {
    var hour1 = time1.split(':')[0];
    var hour2 = time2.split(':')[0];
    var min1 = time1.split(':')[1];
    var min2 = time2.split(':')[1];

    var diff_hour = hour2 - hour1;
    var diff_min = min2 - min1;
    if (diff_hour<0) {
        diff_hour+= 24;
    }
    if (diff_min<0) {
        diff_min+=60;
        diff_hour--;
    } else if(diff_min>=60){
        diff_min-=60;
        diff_hour++;
    }
    return [diff_hour,diff_min]

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM