snippetjavascriptCritical
How to check whether an object is a date?
Viewed 0 times
objecthowcheckdatewhether
Problem
I have an annoying bug in on a webpage:
date.GetMonth() is not a function
So, I suppose that I am doing something wrong. The variable
So, if I want to write defensive code and prevent the date (which is not one) to be formatted, how do I do that?
Thanks!
UPDATE: I don't want to check the format of the date, but I want to be sure that the parameter passed to the method
date.GetMonth() is not a function
So, I suppose that I am doing something wrong. The variable
date is not an object of type Date. How can I check for a datatype in Javascript? I tried to add a if (date), but it doesn't work.function getFormatedDate(date) {
if (date) {
var month = date.GetMonth();
}
}So, if I want to write defensive code and prevent the date (which is not one) to be formatted, how do I do that?
Thanks!
UPDATE: I don't want to check the format of the date, but I want to be sure that the parameter passed to the method
getFormatedDate() is of type Date.Solution
As an alternative to duck typing via
you can use the
This will fail if objects are passed across frame boundaries.
A work-around for this is to check the object's class via
Be aware, that the
JavaScript execution environments (windows, frames, etc.) are each in their own realm. This means that they have different built-ins (different global object, different constructors, etc.). This may result in unexpected results. For instance, [] instanceof window.frames[0].Array will return false, because Array.prototype !== window.frames[0].Array.prototype and arrays in the current realm inherit from the former.
typeof date.getMonth === 'function'you can use the
instanceof operator, i.e. But it will return true for invalid dates too, e.g. new Date('random_string') is also instance of Datedate instanceof DateThis will fail if objects are passed across frame boundaries.
A work-around for this is to check the object's class via
Object.prototype.toString.call(date) === '[object Date]'Be aware, that the
instanceof solution doesn't work when using multiple realms:JavaScript execution environments (windows, frames, etc.) are each in their own realm. This means that they have different built-ins (different global object, different constructors, etc.). This may result in unexpected results. For instance, [] instanceof window.frames[0].Array will return false, because Array.prototype !== window.frames[0].Array.prototype and arrays in the current realm inherit from the former.
Code Snippets
typeof date.getMonth === 'function'date instanceof DateObject.prototype.toString.call(date) === '[object Date]'Context
Stack Overflow Q#643782, score: 1587
Revisions (0)
No revisions yet.