Sometimes, we’ve to check if a JavaScript object is a date object.
In this article, we’ll look at ways to check whether a JavaScript object is a date object.
Checking for Methods that Date Objects Have
We can check for methods that date objects have.
To do this, we can use the typeof
operator.
For instance, we can write:
const date = new Date(2021, 1, 1);
console.log(typeof date.getMonth === 'function')
We check that the getMonth
method is a function by using the typeof
operator to see if it returns 'function'
.
If it’s true
, then we know it’s likely that date
is a Date
instance.
The console log should log true
, so it’s a good chance that it’s a Date
instance.
The instanceof Operator
A more accurate check is to check whether the object is created from the Date
constructor.
If it is, then we know it must be a Date
instance.
For instance, we can write:
const date = new Date(2021, 1, 1);
console.log(date instanceof Date)
to check if date
is created from the Date
constructor with the instanceof
operator.
The left operand is the object we’re checking.
And the right operand is the constructor we’re checking for.
Since date
is created from Date
, the console log should log true
.
To check if an object is created from the Date
constructor across frame boundaries, we can convert it to a string with the toString
method and check its contents.
To do this, we write:
const date = new Date(2021, 1, 1);
console.log(Object.prototype.toString.call(date) === '[object Date]')
We call toString
as Object.prototype.toString.call
since toString
maybe overridden with our own methods.
By calling it this way, we make sure we call the built-in toString
method rather than the one we created.
Check for Invalid Date
If we pass in something that can’t be parsed to a date into the Date
constructor, then it returned 'Invalid Date'
when the object is converted to a string.
So we can check for this by writing:
console.log(new Date('abc').toString() === 'Invalid Date')
We pass in 'abc'
into the Date
constructor, which can’t be parsed to a date.
So when we call toString
, it returns ‘Invalid Date’
.
Therefore, the console log should log true
.
Conclusion
There’re several ways we can use to check for a valid date object or an invalid one with JavaScript.