1

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>

1 Answers1

0

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?

Andrey Popov
  • 7,362
  • 4
  • 38
  • 58
  • I think my code is wrong when I am subtracting ndt from dt because ndt is a date and dt is a string. Can you please solve this issue? – Moosa Imran Sep 08 '21 at 10:58
  • It really depends on the format of the value. If it's some of the regular ones, you can always do `new Date(dt)` so that it's a Date now. But if it's just an input field, then you've got a problem as people might enter any kind of format. If so - then you should check some date library. – Andrey Popov Sep 08 '21 at 11:01
  • Thank You, you are right but the only last confusion that what is the default syntax of date is? – Moosa Imran Sep 08 '21 at 11:14
  • There's no single default, there are many ways to do that: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date – Andrey Popov Sep 08 '21 at 11:18