简体   繁体   中英

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!

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM