Naguib Ihab
Naguib Ihab

Reputation: 4506

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();

Upvotes: 1

Views: 16514

Answers (2)

icktoofay
icktoofay

Reputation: 129139

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());
somethingelse.setDate(17);
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();
date.setDate(17);
document.getElementById("result").innerHTML = date.getDate();

Upvotes: 6

user3581203
user3581203

Reputation: 297

This much is enough: You can take the same today object and set and get date for that object.

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

Fiddle

Upvotes: 2

Related Questions