Categories
JavaScript Answers

How to Detect an “Invalid Date” Date Instance in JavaScript?

Spread the love

If we’re trying to parse JavaScript dates, sometimes we may get ‘invalid date’ values.

If we try to parse invalid date values, then our JavaScript program may crash.

In this article, we’ll look at how to detect an ‘invalid date’ date instance with JavaScript.

instanceof and isNaN

We can combine the use of the instanceof operator and the isNaN function to check for invalid dates.

The instanceof operator lets us whether an object is created from the Date constructor.

And the isNaN function lets us check whether the object converts to a timestamp when we try to cast it to a number.

isNaN tries to cast an object to a number before checking if it’s a number.

For example, we can write:

const isValidDate = (d) => {
  return d instanceof Date && !isNaN(d);
}

const validDate = new Date(2021, 1, 1)
const invalidDate = new Date('abc')
console.log(isValidDate(validDate))
console.log(isValidDate(invalidDate))

to create the isValidDate function which returns the expression d instanceof Date && !isNaN(d); to do both checks.

Then we can call it with validDate and invalidDate , which are valid and invalid date objects respectively.

Date.parse

We can also use the Date.parse method to try to parse a Date instance into a date.

For instance, we can write:

const validDate = new Date(2021, 1, 1)
const invalidDate = new Date('abc')
console.log(!isNaN(Date.parse(validDate)))
console.log(!isNaN(Date.parse(invalidDate)))

Date.parse returns a UNIX timestamp if it’s a valid date.

So if we pass in validDate to Date.parse , we should get an integer timestamp returned.

And if we pass in invalidDate , we should get NaN returned.

This means we can use isNaN again to check whether the result returned by Date.parse is a number.

instanceof and isFinite

We can call isFinite instead of isNaN in our valid date check.

This is because isFinite only returns true if anything that can be converted to a finite number is passed in as an argument.

To use it, we write:

const isValidDate = (d) => {
  return d instanceof Date && isFinite(d);
}
const validDate = new Date(2021, 1, 1)
const invalidDate = new Date('abc')
console.log(isValidDate(validDate))
console.log(isValidDate(invalidDate))

This way, we can get rid of the negation before isNaN , which makes the isValidDate function easier to read.

Conclusion

We can check for valid date objects with the instanceof operator, isNaN , isFinite , or Date.parse .

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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