1

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?

3

2 Answers 2

4

.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

Sign up to request clarification or add additional context in comments.

1 Comment

And the other funny thing is that getMonth() starts with 0 for January and runs through 11 for December (not a problem here, but trips up many people, too).
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.