Search code examples
javascriptdatetimesubtraction

Substracting javascript times


I'm having trouble with substracting times in javascript even though I've been googling for 2 days without any luck :(

I'm trying to time a questionnaire. When the user starts the questionnaire a timestamp is logged. When the user finishes/clicks submit a new timestamp is logged, and the two times are subtracted to find out how much time the user spent.

(For this example I've just been using buttons...) When i subtract i get NaN - Do I need to parse the miliseconds?

Code here: Click

And Here:

var myVar = setInterval(myTimer, 1000);
	function myTimer(){
		var d = new Date();
		document.getElementById("demo").innerHTML = d.toLocaleTimeString();
	}

	function maal1(){
		var tid = new Date();
		document.getElementById("demoo").innerHTML = tid.getTime();
}

	function maal2(){
		var tid = new Date();
		document.getElementById("demooo").innerHTML = tid.getTime();
}

	function calc(){
		var tid1 = document.getElementById("demoo").value;
		var tid2 = document.getElementById("demooo").value;
		var tid3 = tid2 - tid1;
		document.getElementById("tident").innerHTML = tid3;
}
<p class="centercenter" id="demo">Henter...</p></br>

<button class="centercenter" onClick="maal1()">Tid 1</button></br>

<p class="centercenter" id="demoo"></p></br>

<button class="centercenter" onClick="maal2()">Tid 2</button></br>

<p class="centercenter" id="demooo"></p></br>

<button class="centercenter" onClick="calc()">Calc</button></br>

<p class="centercenter" id="tident">Calc here</p>


Solution

  • function calc(){
            var tid1 = parseInt(document.getElementById("demoo").innerHTML) || 0;
            var tid2 = parseInt(document.getElementById("demooo").innerHTML) || 0;
    
            var tid3 = tid2 - tid1;
            document.getElementById("tident").innerHTML = tid3;
    }
    

    Your innerHTML is fine, but it's taken as a string. String minus string = NaN (Not a number)

    Parse to int (or parseFloat for decimals) and it should work.

    (Incidentally, i've added || 0 incase of null strings, edge case I know, but non-breaking)