如何计算javascript中时间输入之间的差异?

时间:2019-02-08 06:54:50

标签: javascript

我想计算我的工作时间。输入

时效果很好
08:00 - 09:00 = 01:00

但是当我这次输入

23:30 - 01:30 = 10:00 

它应该返回02:00

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
  );
}
<input type="time" id="timeOfCall">
<input type="time" id="timeOfResponse">
<button type="button" id="button">CLICK</button>
<input type="time" id="delay">

6 个答案:

答案 0 :(得分:1)

所需算法中最重要的部分是确定结束日期是否是明天。
根据您的代码,这里是我建议的working example

<!DOCTYPE html>
<html>
  <head>
    <style>
    </style>
  </head>
  <body>
    <input type="time" id="timeOfCall">
    <input type="time" id="timeOfResponse">
    <button type="button" id="button" onclick="diffTime()">CLICK
    </button>
    <input type="time" id="delay">
    <script>
      function pad(num) {
        return ("0" + num).slice(-2);
      }
      function diffTime() {
        var start = document.getElementById("timeOfCall").value;
        var end = document.getElementById("timeOfResponse").value;
        // start date will be today
        var d1 = new Date();
        var s = start.split(":")
        var date1 = new      Date(d1.getFullYear(),d1.getMonth(),d1.getDate(),s[0],s[1],0,0);
        var s2 =  end.split(":")
        // end date
        if(s2[0] < s[0])
        {
          // its tommorow...
          var ms = new Date().getTime() + 86400000;
          var tomorrow = new Date(ms);
          d1=tomorrow;
        }
        var date2 = new      Date(d1.getFullYear(),d1.getMonth(),d1.getDate(),s2[0],s2[1],0,0);
        var diff = date2.getTime() - date1.getTime();
        var msec = diff;
        var hh = Math.floor(msec / 1000 / 60 / 60);
        msec -= hh * 1000 * 60 * 60;
        var mm = Math.floor(msec / 1000 / 60);
        msec -= mm * 1000 * 60;
        var ss = Math.floor(msec / 1000);
        msec -= ss * 1000;
        alert(hh + ":" + mm + ":" + ss);
      }
      document.getElementById("timeOfCall").defaultValue = "23:30";
      document.getElementById("timeOfResponse").defaultValue = "01:30";
    </script>
  </body>
</html>

答案 1 :(得分:0)

我将使用Date对象来计算时间差。由于您只对时间感兴趣,因此可以使用任何日期来构造有效的日期字符串。您获得10个小时的原因是因为没有日期显示第二天是凌晨1点(这是根据我对您问题的理解)。

您可以执行以下操作来完成工作。

const pad = num => (num < 10) ? `0${num}` : `${num}`;

const addADay = (start, end) => {
  const sHour = parseInt(start.split(':')[0], 10);
  const eHour = parseInt(end.split(':')[0], 10);
  return (eHour < sHour);
};

const diffTime = (start, end) => {
  const startDate = new Date(`2019/01/01 ${start}:00`);
  const endDate = addADay(start, end) 
    ? new Date(`2019/01/02 ${end}:00`) 
    : new Date(`2019/01/01 ${end}:00`);
  const diff = endDate.getTime() - startDate.getTime();
  const hours = Math.floor(diff / 3600000);
  const min = (diff - (hours * 3600000)) / 60000;
  return `${pad(hours)}:${pad(min)}`;
}

console.log(diffTime('08:00','09:00')); // returns 01:00
console.log(diffTime('23:00','01:30')); // returns 02:30

答案 2 :(得分:0)

您好,我已经稍微更改了您的代码。解释是,让您的开始时间为10:00,结束时间为09:00。现在顺时针思考。时间必须到24小时的9:00。因此,计算结果是24小时与10小时之间的时差,然后加上其余时间。

D = E +(24-S)

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) {
    diff = eMin + (24 * 60 - sMin); /* You had to caculate with 24 hours */
  }
  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
  );
}
<input type="time" id="timeOfCall">
<input type="time" id="timeOfResponse">
<button type="button" id="button">CLICK</button>
<input type="time" id="delay">

答案 3 :(得分:0)

这是解决您所有测试用例的问题的另一种更简单的方法,如果有任何失败的情况,请尝试所有测试用例,然后告诉我我将解决它。

您只需要先花几个小时,然后检查是上午还是下午,然后简单地数分钟即可。

function diffTime(start, end) {
			var s = start.split(":");
			var e = end.split(":");
			var dHour;
			var dMinute ;
			var startHour = parseInt(s[0]);
			var endHour = parseInt(e[0]); 
			var startMinute = parseInt(s[1]);
			var endMinute = parseInt(e[1]);
			
			// For counting difference of hours

			if((startHour>12 && endHour>12) || (startHour<12 && endHour<12))
			{
				
				if(startHour<endHour)
				{
					dHour = endHour - startHour;
				}
				else if(startHour>endHour)
				{
					dHour = 24 - ( startHour - endHour);
				}
				else
				{
					dHour = 24;					
				}
			}
			else if(startHour>12 && endHour<=12)
			{
				dHour = (24 - startHour) + endHour;
			}
			else if(startHour<=12 && endHour > 12)
			{
				dHour = endHour - startHour;
			}
			else 
			{
				dHour = 24
			}


			// For Counting Difference of Minute

			if (startMinute>endMinute) 
			{
				dMinute = 60 - (startMinute - endMinute);
				dHour = dHour - 1;
			}
			else if(startMinute<endMinute)
			{
				dMinute = endMinute - startMinute;
			}
			else
			{
				dMinute = 0
			}

			return dHour + " Hours " + dMinute + " Minutes";
		}

		document.getElementById('button').onclick = function() {
			document.getElementById('delay').value = diffTime(
				document.getElementById('timeOfCall').value,
				document.getElementById('timeOfResponse').value);
}
<input type="time" id="timeOfCall">
<input type="time" id="timeOfResponse">
<button type="button" id="button">CLICK</button>
<input type="text" id="delay">

答案 4 :(得分:0)

谢谢你的朋友,我解决了我的问题,Miraz Chowdhury的代码完成了我的工作

答案 5 :(得分:-1)

function diff(t1, t2) {
  
  const day = 86400000;

function pad(num) {
   return ("0" + num).slice(-2);
}

    let time1 = t1.split(":").map(el => parseInt(el));
    let time2 = t2.split(":").map(el => parseInt(el));

    let zero = (new Date(1990, 0, 1, 0, 0)).setMilliseconds(0)
    let aaa = (new Date(1990, 0, 1, time1[0], time1[1])).setMilliseconds(0)
    let bbb = (new Date(1990, 0, 1, time2[0], time2[1])).setMilliseconds(0)


    let diff =  day -Math.abs(aaa - bbb)<Math.abs(aaa - bbb)?day -Math.abs(aaa - bbb):Math.abs(aaa - bbb)


    return `${pad(Math.round(diff/1000/60/60))}:${pad(Math.abs(Math.round(diff/1000/60%60)))}`;
}

console.log(diff("09:00", "08:00"));
console.log(diff("23:30", "01:30"));
console.log(diff("01:30", "23:30"));