check for is date in javascript code example

Example 1: javascript check if date object

let date1 = new Date();
let date2 = new Date("random string");

(Object.prototype.toString.call(date1) === '[object Date]' && date1 != "Invalid Date") // true
(Object.prototype.toString.call(date2) === '[object Date]' && date2 != "Invalid Date") // false

Example 2: js is date

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