Open In App

How to Check Whether an Object is a Date ?

Last Updated : 20 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

This article will show you how to check whether the given object is a Date or not. There are two methods to check for date objects, which are described below:

Method 1: Using instanceof Operator

The instanceof operator checks whether the prototype property of a constructor appears anywhere in the prototype chain of an object. In this case, it is used to check whether the object is an instance of the Date object or not. A true value means that it does match the object specified. The validity of the date in the Date object can be checked with the !isNan() function. It returns true if the date is not invalid. 

Syntax:

object instanceof Date

Example: 

Javascript




let str = new String('This is a string');
let num = new Number(25);
let date = new Date('13-January-19');
 
let ans = (str instanceof Date) && !isNaN(str);
console.log(ans);
 
ans = (num instanceof Date) && !isNaN(num);
console.log(ans);
 
ans = (date instanceof Date) && !isNaN(date);
console.log(ans);


Output

false
false
true

Method 2: Using Object.prototype.toString.call() Method

The Object.prototype.toString.call() method is used to return the internal class property of an object in a string of the format ‘[object Type]’. This property is assigned internally during the creation of any object. This property can be checked for the Date object by comparing it with the string ‘[object Date]’. A true value means that it does match the object specified. The validity of the date in the Date object can be checked with the !isNan() function. It returns true if the date is not invalid. 

Syntax:

Object.prototype.toString.call(object)

Example: 

Javascript




let str = new String('This is a string');
let num = new Number(25);
let date = new Date('13-January-19');
 
let ans = Object.prototype.toString.call(str)
    === '[object Date]' && !isNaN(str);
console.log(ans);
 
ans = Object.prototype.toString.call(num)
    === '[object Date]' && !isNaN(num);
console.log(ans);
 
ans = Object.prototype.toString.call(date)
    === '[object Date]' && !isNaN(date);
console.log(ans);


Output

false
false
true

We have a complete list of JavaScript Date Objects, to check those please go through this Javascript Date Object Complete reference article.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads