I am new to coding I have confused about the concept of Dates in JavaScript. I need to validate that the user has selected 3 years before's date in the textbox*, but my codes through some errors.* Check The Following Code:
<script>
function run() {
var dt =document.getElementById("dt").value; //Value of selected date
var ndt = new Date(); //Current Date
var diff = ndt.getTime()-dt.getTime();
var milliseconds = 1000 * 60 * 60 * 24;
var result = diff/milliseconds;
if (result > 1095) {
alert("Correct");
} else {
alert("Wrong")
};
}
</script>
Your calculations should be something along the lines:
if (diff > 1000 * 60 * 60 * 24 * 365 * 3)
This is because: 1000ms (is 1 second) * 60 (equals 1 minute) * 60 (equals 1 hour) * 24 (equals one day) * 365 (equals 1 year, roughly) * 3 (equals 3 years).
Surely that's pretty prone to errors! Leap-years are not taken to account, and many more.
I'd suggest you also check this one if you decide to go on a more-stable path: How can I calculate the number of years between two dates?