Open In App

How to check a date is valid or not using JavaScript ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

To check if a date is valid or not in JavaScript, we have to know all the valid formats of the date for e.g.”YYYY/DD/MM”,”DD/MM/YYYY”, and “YYYY-MM-DD”, etc. we will have a given date format and we need to check whether that given format is valid or not according to the official and acceptable date format.

There are two methods to solve this problem which are discussed below: 

Approach 1: Using Custom Method

  • Store the date object in a variable.
  • If the date is valid then the getTime() will always be equal to itself.
  • If the date is Invalid then the getTime() will return NaN which is not equal to itself.
  • The isValid() function is used to check whether the getTime() method is equal to itself.

Example: This example implements the above approach. 

Javascript




const date = new Date("2012/2/30");
 
Date.prototype.isValid = function () {
 
    // If the date object is invalid it
    // will return 'NaN' on getTime()
    // and NaN is never equal to itself
    return this.getTime() === this.getTime();
};
 
function isValidateDate() {
    console.log(date.isValid());
}
 
isValidateDate();


Output

true





Approach 2: Using isNan() Method

  • Store the date object into a variable date.
  • Check if the variable date is created by Date object or not by using Object.prototype.toString.call(d) method.
  • If the date is valid then the getTime() method will always be equal to itself.
  • If the date is Invalid then the getTime() method will return NaN which is not equal to itself.
  • In this example, isValid() method is checking if the getTime() is equal to itself or not.

Example: This example implements the above approach. 

Javascript




const date = new Date("This is not date.");
 
function isValidDate() {
    if (Object.prototype.toString.call(date) ===
    "[object Date]") {
        if (isNaN(date.getTime())) {
            console.log("Invalid Date");
        }
        else {
            console.log("Valid Date");
        }
    }
}
 
isValidDate();


Output

Invalid Date





JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.



Last Updated : 08 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads