Calculate Time Difference with JavaScript

后端 未结 12 1116
有刺的猬
有刺的猬 2020-12-01 13:20

I have two HTML input boxes, that need to calculate the time difference in JavaScript onBlur (since I need it in real time) and insert the result to new input box.

F

12条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-01 13:42

    Depending on what you allow to enter, this one will work. There may be some boundary issues if you want to allow 1am to 1pm

    NOTE: This is NOT using a date objects or moment.js

    function pad(num) {
      return ("0"+num).slice(-2);
    }
    function diffTime(start,end) {
      var s = start.split(":"), sMin = +s[1] + s[0]*60,
          e =   end.split(":"), eMin = +e[1] + e[0]*60,
       diff = eMin-sMin;
      if (diff<0) { sMin-=12*60;  diff = eMin-sMin }
      var h = Math.floor(diff / 60),
          m = diff % 60;
      return "" + pad(h) + ":" + pad(m);
    }  
    document.getElementById('button').onclick=function() {
      document.getElementById('delay').value=diffTime(
          document.getElementById('timeOfCall').value, 
          document.getElementById('timeOfResponse').value
      );
    }
    
    
    
    

提交回复
热议问题