1

I have an issue, and I don´t know what is wrong.

new Date(2017,3,31).getDate() returns 1 (like 1.4., not 31.3.)

new Date(2017,3,30).getDate() returns 30 (as 30.3.), which is correct.

Am I missing something?

3
  • Month starts with 0 for January, and ends with 11 for December MDN: Date Commented May 3, 2017 at 15:07
  • 3 is April and there is no April 31st. Always read the MDN documentation. Commented May 3, 2017 at 15:07
  • This question title is not acceptable; please make it describe the question. Commented May 3, 2017 at 15:29

2 Answers 2

4

Months in JavaScript are zero-based, so Date(2017,3,31) is actually April 31st, which doesn't exist. So you end up with May 1 instead.

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

3 Comments

How so "end up" with May? I think the edit doesn't make sense
@Matheus - JavaScript says hey, there is no April 31, so here's the correct day. As MDN notes: "if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013, 13, 1) is equivalent to new Date(2014, 1, 1), both create a date for 2014-02-01 (note that the month is 0-based). "
aaahh a thought that it is not index (zero) based.. how could I miss that? :D thank you
2

You probably expect 3 to be March as it is the third month of the year.

JavaScript months start at 0:

0 - January
1 - February
2 - March
...

You are trying to create the April 31st, which does not exist. Change it to:

new Date(2017, 2, 31).getDate(); // March 31st

3 Comments

@OndraPernica Well, I think this constructor is ambiguous, you are not the first one to do this mistake... :)
it´s so missleading. Days starts at 1, months at 0.. but ill remember that since now
There is a long tradition of people making this mistake, JavaScript copied it from Java, Java copied it from C... isn't it obvious ;-)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.