0

Hi I searched the web for checking date using javascript. I found the code example How to check whether a JavaScript date is valid?. The date is 2025-2-29 for testing. The code automatedly change to 2025-3-1 and show the date is valid. How can I stop it change the date? The result should be invalid for 2025-2-29

there is my code:

<!DOCTYPE html>
<html>
 <body>

  <h1>JavaScript Dates</h1>
  <h2>Using new Date()</h2>
  <p id="demo"></p>
  <p id = "validate"> </p>
  <script>
    const date = new Date("29Feb2025");
    document.getElementById("demo").innerHTML = date;
    isValid(date);

  function isValid(date) {
      alert(date);
     if ( Object.prototype.toString.call(date) === "[object Date]") {
        if ( !isNaN(date.getTime()) ) {
           validate.innerHTML += date + " is valid. <br/> ";
        } else {
           validate.innerHTML += date + " is not valid. <br/> ";
        }
     } else {
        validate.innerHTML += date + " is not valid. <br/> ";
     }
  }
 </script>

 </body>
</html>

The output:

JavaScript Dates
Using new Date()
Sat Mar 01 2025 00:00:00 GMT-0800 (Pacific Standard Time)

Sat Mar 01 2025 00:00:00 GMT-0800 (Pacific Standard Time) is valid.

Blockquote

Y Chan
  • 317
  • 2
  • 18
  • Does this answer your question? [How to validate a date?](https://stackoverflow.com/questions/5812220/how-to-validate-a-date) – Alex Berger Feb 28 '23 at 14:39
  • 1
    There is no 29 Feb in 2025. If you want to preserve the invalid string source of the date, keep it around as a string. The native behavior of the JavaScript Date API is to "fix" dates that make no sense. In your case, the day after 28 Feb in 2025 is 1 Mar. – Pointy Feb 28 '23 at 14:42
  • yeah when you use `new Date("29Feb2025");` it fixes the date for you – Chris G Feb 28 '23 at 14:48

0 Answers0