Explain Codes LogoExplain Codes Logo

How to check whether an object is a date?

javascript
date-validation
defensive-programming
javascript-best-practices
Alex KataevbyAlex Kataev·Jan 1, 2025
TLDR

Find out if an object is a Date by utilizing the Object.prototype.toString.call method. If it fetches "[object Date]", it's a Date. Here's a short and efficient example:

const isDate = obj => Object.prototype.toString.call(obj) === '[object Date]';

Test it out:

console.log(isDate(new Date())); // true - it's a date alright console.log(isDate({})); // false - just an empty object chillin'

Drawing the line for instanceof

Though instanceof Date may seem handy to check for Date objects, tread with caution. Unfortunately, it also yields true for invalid dates. E.g.,

console.log(new Date('nope') instanceof Date); // true - but wait, this isn't a date!

Evade these pitfalls through defensive programming to prevent wrong formation of Date objects when non-Date types are passed into new Date().

Consistent cross-frame checks

Ensuring cross-frame compatibility in JavaScript can be a challenge but Object.prototype.toString.call() happens to fill in that gap. Pay heed to the case sensitivity of methods like date.getMonth. It has to be getMonth, not GetMonth.

Drawing the line: invalid dates

Detecting if a Date is legit requires !isNaN(date) and the assurance that the object resembles a date, like having a getMonth method:

const isValidDate = date => { return isDate(date) && !isNaN(date) && typeof date.getMonth === 'function'; }; console.log(isValidDate(new Date())); // true - Good job, you're a date! console.log(isValidDate(new Date('foo'))); // false - Nice try! But no cigar.

This extra check guards against the infamous "Invalid Date" mischief-maker.

Ensuring actual Date objects

Defensive coding is paramount when fiddling with dates. Prevent formatting non-date values by always keeping checks and balances in place:

function formatDate(date) { if (!isValidDate(date)) { // Gentle alert for the mixing of apples and oranges! throw new TypeError('You're trying to feed a date to a hungry string formatter. Feed it time, not type!'); } // Carry on formatting }

Such safeguards help keep those pesky date-related bugs under control.

Duck typing with dates

"Duck typing" — if it quacks like a duck, it could be a Date object! Here we check whether the object has a specific method: getMonth:

const isDateDuckTyped = obj => typeof obj.getMonth === 'function';

Remember, in some cases, we just need a duck-like figure, so it’s okay if it's not an actual mallard but our friendly neighbourhood Date object!

Case study: best practices

Stay wary of edge cases and enforce more checks for invalid dates, especially when supporting complex contexts. Following capitalization of methods, and preventing non-Date types to new Date() may seem mundane but ensures accurate Date detection.