Open In App

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

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

Example: This example implements the above approach. 






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

Example: This example implements the above approach. 




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.


Article Tags :