Ondra Pernica
Ondra Pernica

Reputation: 33

JS - Date issue with constructor

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?

Upvotes: 1

Views: 57

Answers (2)

Mistalis
Mistalis

Reputation: 18269

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

Upvotes: 2

j08691
j08691

Reputation: 207861

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.

Upvotes: 4

Related Questions