Friday, 29 September 2017

javascript - How to check whether an object is a date?



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 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.


Answer



As an alternative to duck typing via



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 Date




date instanceof Date


This 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]'


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...