Explain Codes LogoExplain Codes Logo

Detecting an "invalid date" Date instance in JavaScript

javascript
date-validation
javascript-best-practices
performance-optimization
Anton ShumikhinbyAnton Shumikhin·Sep 26, 2024
TLDR

Detect an invalid Date instance by checking if its getTime() method returns **NaN via Number.isNaN():

// The quickest way to stop invalid dates ruining your day, or code const dateIsValid = (date) => !Number.isNaN(date.getTime()); // Usage: console.log(dateIsValid(new Date('2023-04-01'))); // true console.log(dateIsValid(new Date('bad date'))); // false, kinda like ketchup on a pizza

This one-liner directly iron out invalid dates with the least verbosity.

Unpacking the date instance validation

Types matter in JavaScript, especially when dealing with dates. We can reinforce the date type checking using Object.prototype.toString.

// Making sure that our date is really a date const isDateObject = (d) => Object.prototype.toString.call(d) === "[object Date]";

For cross-contextual validations (e.g., iframe or different window), use a more comprehensive check:

// When your date has too much context, verify it like this const isValidDateObject = (d) => { return d instanceof Date && !isNaN(d) && Object.prototype.toString.call(d) === "[object Date]"; };

Now, strings, they can be nasty. So, ensure to parse them correctly before assuming they are dates.

// Because not every "30th of February" can be a legit date const dateStringIsValid = (dateString) => { const timestamp = Date.parse(dateString); return !Number.isNaN(timestamp); };

Checking date validity: The easy path

Pimp your Date prototype with a custom-made isValid method.

// Hooking up an 'isValid' function to all your dates, because...why not? Date.prototype.isValid = function() { return !Number.isNaN(this.getTime()); }; // Usage: const myDate = new Date('2023-04-01'); console.log(myDate.isValid()); // true const notMyDate = new Date('bad date'); console.log(notMyDate.isValid()); // false, goes well with pineapple on pizza

Some thumb rules to avoid facepalm moments while validating dates:

  • Be wary of constructor overload: The flexibility of JavaScript Date might lead to unexpected results.
  • Stick to UTC for consistent outcomes: Date.UTC() and UTC instance methods are your friends for time zone complications.
  • When native JavaScript isn't enough, there's no shame in using a trustworthy third-party library for complex date manipulations and validations.

Keeping an eye on performance

Let's not get carried away with brevity and forget about performance considerations:

  • Direct methods like getTime(), Number.isNaN(date) over indirect checks are like taking the fast lane on a highway.
  • Minimize function calls by inlining validations, especially when performance is critical.
  • Keep a profiling tool handy to ensure date validations aren't slowing you down.