Ramy CoreMT
Ramy CoreMT

Reputation: 83

Calculate time difference from two time inputs in HH:MM:SS format in Javascript

I am trying to calculate the time difference of what a user inputs in my HTML form. The JavaScript in turn should show the user in real time what the difference is while also returning the value into an hidden input.
Here is the HTML:

<input type="time" id="timeOne" name="timeOne" value="00:00:01" step="1"  onchange="timeFunction()">    
<input type="time" id="timeTwo" name="timeTwo" value="00:00:01" step="1"  onchange="timeFunction()">
<b>Time Difference: </b> <p id="timeDifference">--:--:--</p>
<input type="hidden" id="timeDiff" name="timeDiff">

How can I go about doing this? I have attempted this method but receive a NaN error. I am also unsure how to put it back together to return the time difference into the hidden input should this work.

function timeFunction(){
 var timeOneValue = document.getElementById("timeOne").value;
 var timeTwoValue = document.getElementById("timeTwo").value;

 var res = Math.abs(timeTwoValue - timeOneValue) / 1000;                          
 // get hours        
 var hours = Math.floor(res / 3600) % 24;        
      
 // get minutes
 var minutes = Math.floor(res / 60) % 60; 
  
 // get seconds
 var seconds = res % 60;  
      
 document.getElementById("timeDifference").innerHTML = (hours + ":" + minutes + ":" + seconds);
}

Upvotes: 1

Views: 1553

Answers (2)

Unmitigated
Unmitigated

Reputation: 89254

You can split each time string on : and then convert it to seconds in order to calculate the difference.

function timeFunction() {
  const getSeconds = s => s.split(":").reduce((acc, curr) => acc * 60 + +curr, 0);
  var seconds1 = getSeconds(document.getElementById("timeOne").value);
  var seconds2 = getSeconds(document.getElementById("timeTwo").value);

  var res = Math.abs(seconds2 - seconds1);

  var hours = Math.floor(res / 3600);

  var minutes = Math.floor(res % 3600 / 60);

  var seconds = res % 60;
  document.getElementById("timeDifference").innerHTML = hours + ":" + minutes + ":" + seconds;
}
<input type="time" id="timeOne" name="timeOne" value="00:00:01" step="1" onchange="timeFunction()">
<input type="time" id="timeTwo" name="timeTwo" value="00:00:01" step="1" onchange="timeFunction()">
<b>Time Difference: </b>
<p id="timeDifference">--:--:--</p>
<input type="hidden" id="timeDiff" name="timeDiff">

Upvotes: 3

Marc Majcher
Marc Majcher

Reputation: 11

The problem is likely that you're getting text/strings from your HTML element .values, and you need to convert them into numbers (with parseInt() or somesuch) to do math on them.

Upvotes: 0

Related Questions