Reputation: 145
I'm sorry but the new Date()
is not returning an object as I understand an object.
From the MDN article on Date
constructor :
When no parameters are provided, the newly-created Date object represents the current date and time as of the time of instantiation.
(emphasis added)
All right then, where is the object there :
const date1 = new Date();
console.log(date1);
// returns Wed Jan 27 2021 15:45:31 GMT+0100
An object would be
{date: "Wed Jan 27 2021 15:45:31 GMT+0100")}
But it looks more like a string, BUT we can't manipulate it like a string, since :
const date1 = new Date();
console.log(date1[0]); // expecting "W"
// returns undefined
I know how to manipulate this special format with the different time methods but this has always been a mystery for me.
What is this format ?
Another Type ?
And why there is no object returned by the constructor new Date()
?
Upvotes: 2
Views: 818
Reputation: 3055
When calling new Date()
, you will get a date object. When calling console.log(new Date())
, the toString
-method of the date object will implicitly get called (not 100% true, but you get the idea). How the console
-object works, is implemented by your browser/enironment. My guess is showing the date as a string is a convenience they've build in.
Like others have mentioned in the comments, try console.log(typeof new Date())
/console.dir(new Date())
or to call any of the methods documented. You'll see it is most definitely an object.
Upvotes: 2
Reputation: 459
While there is a string returned by the "console.log(date)", the "date" variable itself is actually an object. It's just there so that if you wanted to print out the date quickly, then you would do "console.log(date)". However,for this you cannot do any manipulations. You would have to look at the methods of the "Date" class. There are many other functions within it that allow you to get specific information.
For example:
date.getMonth()
date.getDay();
date.getYear();
This Date constructor has functions of it's own which make it easier. So, you don't have to reference the values of the object itself. All you have to do is type these commands at it should automatically give you the information you need.
This documentation is available at : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Just scroll down to "INSTANCE METHODS" and all the methods should be available there.
Upvotes: 0