Naguib Ihab Naguib Ihab -4 years ago 95
Javascript Question

Javascript date undefined error

this is my code and I'm getting "Uncaught TypeError: undefined is not a function" what am i doing wrong?

var myDate = new Date().setDate(17);
document.getElementById("result").innerHTML = myDate.getDate();

Answer Source

setDate modifies the object it is called on and returns undefined. If you want to make somethingelse refer to the date that today referred to, but changing the day, you could copy today and then change somethingelse:

var today = new Date();
var somethingelse = new Date(today.getTime());
document.getElementById("result").innerHTML = somethingelse.getDate();

Of course, if you didn’t care about preserving what was in today, you could certainly modify that without creating a copy.

var date = new Date();
document.getElementById("result").innerHTML = date.getDate();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download