Sometimes while using this constructor I am getting incorrect values:
new Date(year, month, day, hours, minutes, seconds, milliseconds);
I'm sure it is something I'm doing incorrectly, but can't see it. This is what I'm doing:
I have an array with month, day, and year indexes like this
["02", "29", "2015"]
Then I am making a Date object like this
date = new Date(dateArray[2], dateArray[0] - 1, dateArray[1], 0, 0, 0, 0);
When I print the date object to the console, I get this:
Sun Mar 01 2015 00:00:00 GMT-0700 (MST)
Sometimes however it works as expected. Using this array:
["03", "15", "2015"]
I get this:
Sun Mar 15 2015 00:00:00 GMT-0600 (MDT)
Can anyone see what I am doing incorrectly here?
Thanks in advance
Because there is no February 29 in 2015! That's not a leap year. The day after February 28 is March 1st. This is the expected behavior.
The precise behavior is defined in §15.9.1.5 of the ECMAScript 5.1 specification.
In Javascript, month is 0-based, so if you call Date.getMonth(), you get a value between 0 - 11, Date.getDate() returns day of the month between 1 - 31, Date.getDay() returns day of the week between 0 - 6 with 0 for Sunday. So in your case, the month 02 is march, but you minus it by 1 which results in 01 which is February and depends on leap year, you have 29 days or not. Because the year is 2015, February is only 28 days, but you specified 29 for the day, that is why month is rolled over to March 01
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With