0

I am not able to use the .getTime() method, can someone help me? Error message in link! The original date is just from basic html date input.

JS:

document.getElementById("lastMenDate").addEventListener("change", function () {
    var inputMen = this.value;
    var lastMenDate = new Date(inputMen);
    console.log(lastMenDate);
});

document.getElementById("targetDate").addEventListener("change", function () {
    var inputTar = this.value;
    var targetDate = new Date(inputTar);
    console.log(targetDate);
});

document.getElementById("calc").addEventListener("click", function () {
    var timeDifference = targetDate.getTime() - lastMenDate.getTime();
    var daysDifference = timeDifference / (1000 * 24 * 60 * 60);
    console.log(daysDifference);
});

error

1 Answers1

1

as commented, your vars are not scoped to the window / "all functions", so you can just assign your variable to the window/global and reference it that way. You could also look at creating an object which employs the calculation.

document.getElementById("lastMenDate").addEventListener("change", function () {
    var inputMen = window.inputMen = this.value;
    var lastMenDate = window.lastMenDate = new Date(inputMen);
    console.log(lastMenDate);
});

document.getElementById("targetDate").addEventListener("change", function () {
    var inputTar = window.inputTar = this.value;
    var targetDate = window.targetDate = new Date(inputTar);
    console.log(targetDate);
});

document.getElementById("calc").addEventListener("click", function () {
    var timeDifference = window.timeDifference = window.targetDate.getTime() - window.lastMenDate.getTime();
    var daysDifference = window.daysDifference = timeDifference / (1000 * 24 * 60 * 60);
    console.log(daysDifference);
});
This Guy
  • 495
  • 4
  • 9
  • Thank you so much, I didn't realize! – Jáchym Plánička Sep 01 '22 at 20:06
  • You are welcome. This may not be the best way to accomplish what you would like, but it is a nudge in the right direction based on where you are currently. Think about creating an object with properties of "lastMenDate", "targetDate", "timeDifference" and use those to expose the calculation for "daysDifference". then you can modify your EventListeners to change that objects properties. A basic implementation of that would prevent you from "polluting" the global scope. – This Guy Sep 01 '22 at 20:17