Home > Blockchain >  Can any one help me on Date method of JS?
Can any one help me on Date method of JS?

Time:04-06

This is my HTML body section. I use onClick Method on button. Here i want the total duration of two days. My code is not working.

    <input type="date" id="d1">
    <input type="date" id="d2">
    <button onClick="calCulateDays">Get Difference</button>
    <p id="output">Hi</p>

This is Script Section

    function calCulateDays() {
        var d1 = document.getElementById("#d1").value;
        var d2 = document.getElementById("#d2").value;
        const dateOne = new Date(d1);
        const dateTwo = new Date(d2);
        const time = Math.abs(dateTwo - dateOne);
        const days = Math.ceil(time / (1000 * 60 * 60 * 24));
        document.getElementById("#output").innerHTML = days;
    }

CodePudding user response:

document.getElementById() expects just the ID without the '#', as @Barmer said it's weird that you called it 'calCulateDays' instead of 'calculateDays' thats why i adjusted that:

function calculateDays() {

    // Note i changed 'getElementById("#d1")' to 'getElementById("d1")'

    var d1 = document.getElementById("d1").value;
    var d2 = document.getElementById("d2").value;
    const dateOne = new Date(d1);
    const dateTwo = new Date(d2);
    const time = Math.abs(dateTwo - dateOne);
    const days = Math.ceil(time / (1000 * 60 * 60 * 24));

    // same here remove the '#'
    document.getElementById("output").innerHTML = days;

}

Here is the HTML:

<input type="date" id="d1">
<input type="date" id="d2">

// added () to the function name
<button onClick="calculateDays()">Get Difference</button>
<p id="output">Hi</p>
  • Related