Julie Song
Julie Song

Reputation: 13

How to find difference between two times in javascript?

So I need to find the difference between two given times from an html form in javascript.

So far, my code has been returning "undefined".

Here's the code. the times are from a datetime-local input in the form, so they're in the format of mm/dd/yyyy 00:00 AM/PM

function ready() {

    submit.onclick = function () { 
        var timeo = document.getElementById("first");
        var timet = document.getElementById("second");
        console.log(timeo);
        console.log(timet);
        var diff = Math.abs(new Date(timet) - new Date(timeo));

        let el = document.createElement('p')
        el.innerHTML = "Your elapsed time was: " + diff.getTime;
        console.log("worked");
        results.append(el);
    }
}

document.addEventListener("DOMContentLoaded", ready);

Please help!

Upvotes: 0

Views: 73

Answers (1)

Mamun
Mamun

Reputation: 68933

timeo and timet are the elements themselves, you should take the value from the elements:

var timeo = document.getElementById("first").value;
var timet = document.getElementById("second").value;

Upvotes: 2

Related Questions