Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type of Date object

I just read this article on W3Schools about type conversion in JS. There stands:

There are 3 types of objects:

  • Object
  • Date
  • Array

This confused me because to my knowledge there isn't any difference between Date objects and any other object (typeof (new Date()) returns "object"). First I thought that it's special because it contains native code, but there are dozens of functions with native code.

Is this article wrong? Or could anybody tell my why the Date object is so extraordinary that it's considered a separate type of object?

like image 530
Aloso Avatar asked Apr 25 '16 09:04

Aloso


People also ask

What are date objects?

The Date object is an inbuilt datatype of JavaScript language. It is used to work with dates and times. The Date object is created by using new keyword, i.e. new Date(). The Date object can be used date and time in terms of millisecond precision within 100 million days before or after 1/1/1970.

How do I know the type of a date?

You can use the ! isNaN() function to check whether a date is valid. If x is a Date, isNaN(x) is equivalent to Number.

How do you write a date object?

You can create a Date object using the Date() constructor of java. util. Date constructor as shown in the following example. The object created using this constructor represents the current time.


2 Answers

Lemme tell you a basic thing. The articles in W3Schools are definitely outdated so you must not rely on it. Yes, when you give this in console:

typeof (new Date())

The above code returns object because the JavaScript has only a few primitive types:

You can check if it is a date object or not using:

(new Date()) instanceof Date

The above code will return true. This is the right way of checking if the particular variable is an instance of a particular type.

like image 56
Praveen Kumar Purushothaman Avatar answered Sep 28 '22 04:09

Praveen Kumar Purushothaman


You might check an object for being an instance of a specific type also by verifying whether it has a method that is specific to the object type in question:

if (myobject.hasOwnProperty("getUTCMilliseconds")) {
    // myobject is a Date...

The same technique may help you identifying arrays in Javascript:
checking

typeof(myobject)  

yields "object", not "array" if myobject is really an array, so I use

if (myobject.hasOwnProperty("slice")) {
    // we are dealing with an array here ...
like image 30
elwood Avatar answered Sep 28 '22 04:09

elwood