Saturday, November 16, 2024
Google search engine
HomeLanguagesJavascriptHow to Check Whether an Object is a Date ?

How to Check Whether an Object is a Date ?

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.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments