How to Detect Invalid Date in JavaScript

Almost every website and web application heavily uses dates to record, store and display user information. If these dates are not correct and valid, then they can misguide users and even cause bugs in your website. Often JavaScript developers are not clear how to check if a JavaScript date is valid or not. In this article, we will learn how to detect invalid date in JavaScript.

Why Check if Date is Valid

Most website uses dates to store user registration, login, and transactions. They are often retrieved from backend databases and displayed on web pages, or submitted to web server using forms. If these dates are not valid or correct then they can confuse users and even cause your site to perform erroneously. For example, if you do not correctly record the date of payment, then you may not know when you received the money, when a user placed an order. Similarly, if you do not correctly store the date of user logins and activity then it will be difficult to understand user behavior, or identify malicious users.

How to Detect Invalid Date in JavaScript

Here are a couple of simple ways to detect invalid date in JavaScript. There are a couple of different ways in which JavaScript developers need to work with date information. It is either available as Date object, or as a string. Depending on the type of data used to store date information, you need to use a different approach.

1. For Date Objects

If you receive date as object, then first you need to check if it is even a valid Date object or not. If it is a Date object, then you need to check if it is a valid date or not.

There are two ways to check if an object is a Date object or not – using instanceof and using call() function. Here is an example illustrating both.

var d = new Date('2024-01-01');
console.log(d instanceof Date); // output is true
OR
console.log(Object.prototype.toString.call(d) === "[object Date]"); // output is true

Please note, this will only check if the variable has Date data type. If your data is not of Date type, then the above code will return false.

var d = 'abc';
console.log(d instanceof Date); // output is false
OR
console.log(Object.prototype.toString.call(d) === "[object Date]"); // output is false

It does not check if the date is valid. For example, the above code will return true even if it is an invalid Date object.

var d = new Date('abc');
console.log(d instanceof Date); // output is true
OR
console.log(Object.prototype.toString.call(d) === "[object Date]"); // output is true

Once we have determined if the data available to us is a Date object or not, then we will have to further check if it is a valid Date object or not. You can do this using isNaN() function. It returns false for valid dates and true for invalid date objects.

var d = new Date('2024-01-01');
console.log(!isNaN(d)); // output is true

var d = new Date('abc');
console.log(!isNaN(d)); // output is false

Combining the two checks together, here is how we can check if a given variable is a valid Date object or not.

var d = new Date('2024-01-01');
console.log(d instanceof Date && !isNaN(d)); // output is true
OR
console.log(Object.prototype.toString.call(d) === "[object Date]" && !isNaN(d)); // output is true

If you have received invalid date object then the above method will give output as false. However, it will not check if the date value is valid or not, it will only check if it is a valid Date object. To check if it is a valid date or not, check step #3 below.

2. For Date Strings

Sometimes, you may get date values as strings. In this case, if you want to check if it is a valid date, then simply try to create a Date object using this string, with the help of Date constructor. If it is a valid date, then the constructor will return a proper Date object with date and timestamp information in it. Otherwise, it will return an invalid date object.

var date_string = "2024/05/15"; // YYYY/MM/DD format
var date_obj = new Date(date_string);
console.log(date_obj); // output is 2024-05-15T00:00:00.000Z

var date_string = "2024/15/15"; // YYYY/MM/DD format
var date_obj = new Date(date_string);
console.log(date_obj); // Invalid Date

In the above code, we have seen two examples – the first one being a valid date and the second one being an invalid date.

Once you have called a Date constructor on a string, then you can check whether the Date object returned from it is invalid or not. This will tell you whether your date is valid or not. For this purpose, you can use instanceof and isNaN() function as described in previous solution.

This solution works if your date is in YYYY/MM/DD format or MM/DD/YYYY format. But it will return an invalid Date object if it is in DD/MM/YYYY format.

var date_string = "05/15/2024"; // MM/DD/YYYY format
var date_obj = new Date(date_string);
console.log(date_obj); // 2024-05-15T00:00:00.000Z

var date_string = "15/05/2024"; // YYYY/MM/DD format
var date_obj = new Date(date_string);
console.log(date_obj); // Invalid Date

In this case, you will need to first convert your date string to YYYY/MM/DD format or MM/DD/YYYY format and then check if it is valid or not. For this purpose, we first split the date into day, month and year, using split() function and ‘/’ delimiter. You can change the delimiter depending on your date’s format.

var date_string = "15/05/2024"; // DD/MM/YYYY format
var date_array = date_string.split("/");
var new_string = `${date_array[2]}/${date_array[1]}/${date_array[0]}`;

console.log(new_string); // 2024/05/15 (YYYY/MM/DD)

Once you have the date in YYYY/MM/DD or MM/DD/YYYY format, then you can use Date constructor to convert it into a Date object and check if it is valid or not.

3. Check if Date is Valid

So far, we have seen cases where we only check if a Date object is valid or not. We do not check if the date itself is valid. For example, the date ‘2024-02-31’ is invalid since Feb does not have 31 days. Still, if you convert it into a Date object, it will not return an invalid date. It may convert the string into another valid date.

var date_string = "02/31/2024"; // YYYY/MM/DD format
var date_obj = new Date(date_string);
console.log(date_obj); // 2024-03-02T00:00:00.000Z

If this case, you need to split the date into year, month and day and specifically check whether the combination of day and month is valid.

function check_date(date_string){

var date_string = "02/31/2024"; // MM/DD/YYYY format
var date_array = date_string.split("/");\
var day = date_array[0];
var month = date_array[1];

if (month < 1 || month > 12 || day < 1 || day > 31) {
return false;
}

if ((month === 4 || month === 6 || month === 9 || month === 11) && day === 31) {
return false;
}

if (month === 2) { // check for leap year
var leap = (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0));
if (day > 29 || (day === 29 && !leap)) {
return false;
}
}

return true;
}

function check_date("02/31/2024"); // output is false

In the above function, first we split date string input as month and day. Then we check if month value is between 1 and 12, both inclusive and day value is between 1 and 31, both inclusive. Otherwise, it is an invalid date.

Next, we check if the day value is more than 30 for April, June, Sep, and Nov since these months can have only 30 days. Next, we check if the month=2 that is Feb. If so, we first check if it is a leap year. If it is a leap year and day> 29 and if it is not a leap year and day=29, then it is an invalid date.

Conclusion

In this article, we have learnt how to detect invalid date using JavaScript. Since date information can be available as a Date object or date string, we have considered both use cases. We have learnt how to check if a Date object itself is valid or not. Then we learnt how to check if a date string is valid or not. Sometimes, even if the date string is invalid (e.g. 2024-02-31), still the date object might be valid. So we have also learnt how to check if the date string represents a valid date. You can use any of these solutions as per your requirement.

Also read:

How to Find Sum of Array of Numbers in JavaScript
How to Search for Object in Array of JS Objects
How to Add Elements to Beginning of JS Array

Leave a Reply

Your email address will not be published. Required fields are marked *