user1968030
user1968030

Reputation:

Why JavaScript Date object constructor doesn't work correctly?

Look at this code:

var date = new Date();
console.log(date);
// Tue Apr 30 2013 14:24:49 GMT+0430

var date2 = new Date(
    date.getFullYear(),
    date.getMonth(),
    date.getDay(), 0, 0, 0, 0
)
console.log(date2)
// Tue Apr 02 2013 00:00:00 GMT+0430

I simply extracted some date from today's date, and created another date with that data, and the result is another date, not today. What's wrong with JavaScript's Date object?

Upvotes: 1

Views: 515

Answers (2)

maxgalbu
maxgalbu

Reputation: 438

getDay() returns the day of the week (from 0 to 6), not the day of the month (1-31). the correct method is getDate():

var date = new Date();
console.log(date);
// Tue Apr 30 2013 14:24:49 GMT+0430

var date2 = new Date(
    date.getFullYear(),
    date.getMonth(),
    date.getDate(), 0, 0, 0, 0
)
console.log(date2)
// Tue Apr 30 2013 00:00:00 GMT+0430

Upvotes: 1

Osiris
Osiris

Reputation: 4185

.getDay() returns the day of the week (0-6), not day of the month. (It returns 2 for Tuesday)

Use getDate() - it will return 30

Upvotes: 4

Related Questions