Often JavaScript developers need to work with date and time values for their websites and apps. While working with dates, it is important to first check if it is a valid date or not. Otherwise, it can throw an error and stop JavaScript code execution on your web page. There are several ways to do this. In this article, we will learn how to detect invalid date in JavaScript.
How to Detect Invalid Date in JavaScript
Please note, there is a difference between an invalid date such as 2022-12-32 and an invalid date object. In this article, we will learn how to determine if a date object is valid or not.
Here is a simple code snippet to easily check if a date object is valid or not.
if (Object.prototype.toString.call(s) === "[object Date]") { // it is a date if (isNaN(s)) { // s.getTime() or s.valueOf() will also work // date object is not valid } else { // date object is valid } } else { // not a date object }
In the above code, we first check if the given date variable ‘s’ is a date object, by comparing its data type with that of a date object. If so, we check if it is a valid date object or not, using isNaN() function. The isNaN() function checks if a variable is Not A Number. If it is not a number, then it is converted into a number. When you call isNaN() function on date variable it is converted into milliseconds. So if isNaN() returns false, it is not a date.
Alternatively, you can also use the following function to detect invalid dates in JavaScript.
function isValidDate(d) { return d instanceof Date && !isNaN(d); }
The above function checks if the given variable is an instance of Date object and is not NaN. The instanceof function is used to check if a variable is created using a specific constructor, that is, Date constructor, in this case. But this approach may not work across windows, frames or iframes. In such cases, use the first method mentioned above.
In this article, we have learnt how to check if a date is valid or not in JavaScript.
Also read:
Forbidden Characters in Windows & Linux Filenames
MySQL Date Format in DD/MM/YYYY
How to Fix MySQL Error 1153
How to Create Temporary Table in MySQL SELECT Query
How to Select Multiple Columns in Python Pandas
Related posts:
How to Check if Variable is Object in JS
How to Detect Scroll Direction in JavaScript
How to Get Property Values of JS Objects
Return False vs PreventDefault in JavaScript
How to Check if JS Object Has Property
How to Replace Line Breaks With <br> in JavaScript
How to Detect Tab/Browser Closing in JavaScript
How to Automatically Scroll to Bottom of Page in JS
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.