Mikey Mikey - 1 year ago 107
Javascript Question

Why does setFullYear method concatonated to new Date() return milliseconds?

I was playing around with some code and to shorten my code I wanted to do something like this:

//This sets the date to milliseconds
document.getElementById('date').innerHTML= new Date().setFullYear(2020);

//This sets the date to GMT date notation
var d = new Date();

document.getElementById('date').innerHTML= d;

What is going on here? Why can't I concatonate and directly call the method on the new Date method. Weird thing is that it tries to do something but fails somehow and falls back to milliseconds. Someone can shed some light on it?

See fiddle: https://jsfiddle.net/5atb3qtv/

Answer Source

It's because in the first case you're alerting the return value of calling the .setFullYear method, which returns a value in milliseconds. In the second example, you're alerting a Date object, on which the .toString method will be called, resulting in the date format you see.


If you're still confused about why the return value of the method is given instead of the date in case one, think of it like this: if you call a method of an object like document.getElementById, you expect to get the result of calling that method are the return value, in this case an Element. You wouldn't expect to get document back. It's the same in your case. You're calling (new Date()).setFullYear() which returns a number and expecting it to return the date object it's a member of, which wouldn't make sense.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download