Detecting invalid dates in JavaScript
George Mandis
Posted on July 1, 2019
When you want to instantiate a new instance of a JavaScript date object you can pass along date information as a string like this:
new Date('June 27, 2019')
In fact, it's somewhat forgiving in accepting a variety of date formats. All of these in Chrome 75 as of this writing are valid ways to create a date object:
new Date('June 27, 2019')
new Date('2019, June 27')
new Date('2019/06/27')
new Date('6/27/19')
new Date('6-27-19')
new Date('6/27/2019')
new Date('6-27-19')
new Date('2019-06-27')
new Date('6/27/19 11:00')
new Date('2019-06-27')
For production I wouldn't suggest doing this. I'd suggest leaning on an established library like Moment.js or one of the many smaller alternatives suggested in this GitHub repository. But if you're just experimenting with something and need a quick-and-dirty solution to creating a date object, knowing you can do this is handy.
It's also handy to know if you've accidentally created an invalid date. Looking at the output in the console, this seemed like this should be easy:
new Date('My Birthday')
// Invalid Date
You might expect to be able to do something like this:
const birthday = new Date('My Birthday')
if (birthday === "Invalid Date") { ... }
But you would be mistaken! While it's generally considered a best practice to test for strict equality and use that triple equals sign, it's not helping you here. The value spit out to the console isn't actually a string, strange as that might seem.
Technically, this will work:
if (birthday == "Invalid Date") { ... }
But I don't fully trust it and am not sure about support in older browsers.
What's helpful to remember is that the date object is just a number, provided it's formatted right:
const day1 = new Date('June 27, 2019')
const day2 = new Date('My Birthday')
console.log(day1.valueOf())
// 1561618800000
console.log(day2.valueOf())
// NaN
That means we can use the delightfully bizarre isNaN() function to figure out if our date is formatted correctly or not:
if (isNaN(birthday)) { ... }
Voilà.
If you're new to all of this JavaScript/Date/NaN chicanery, I'll leave you with this to copy-and-paste into your console:
typeof NaN
Posted on July 1, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.