JavaScript Objects and Date()

Viewed 53

Why should a variable be defined as an object with the keyword new for a Date()? Over time I realized that if I do not define the variable as an object then I can not use JavaScript Get Date Methods for Date(), but why? When I write typeof Date() It returns a string. If it returns a string then it's like writing var d = new String("October 13, 2014 11:13:00") but if we use one of the methods this date will only work on

var d = new Date();
document.getElementById("demo").innerHTML = d.getFullYear();

Although both var d = new Date(); and var d = new String(); return the string, the method will only work on Date(). It's a bit confusing that the "October 13, 2014 11:13:00" string is saved in a variable that is an object, in both cases.

Why can I only call methods like getFullYear() on a date created by new Date() not by new String("October 13, 2014 11:13:00")?

1 Answers

Date() - returns a string representation of the current date and time. It can be used to get only current date and time, any arguments will be ignored. Whether to use it or not is really depends on the task you need to resolve. So if you are interested only in current date and time and you are not going to "parse" it somehow (extract some part of it, increase or decrease it ...) this is your choice

new Date() - as you have mentioned returns an object that represents the current date and time. But it is much more flexible since you can specify an arguments based on which instance of Date will be created (so you can create any date in future or past). Also you have a bunch of methods to manipulate created date object.

new String() - has nothing to do with date. It is one of the possible options to create string from passed argument or an empty string if one was not provided.

You can read more details about Date object here: https://www.javascripture.com/Date

Related