Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
181
rated 0 times [  183] [ 2]  / answers: 1 / hits: 55954  / 12 Years ago, mon, february 4, 2013, 12:00:00

A Date object’s getMonth() method seems to have a bug. Assuming the Date d is 2013-01-31, I attempt to set the month on d like this:


const d = new Date(); // 2013-01-31

d.setMonth(8);
console.log(d.getMonth());

The result is 9. Why? I tested this both in Chrome and Firefox.


I found out that when it’s the 31st, 30th, or 29th of a month, setting the date to a month that has a fewer number of days causes getMonth to return the wrong value.


More From » date

 Answers
22

Let's break this down:



var d = new Date(); // date is now 2013-01-31
d.setMonth(1); // date is now 2013-02-31, which is 3 days past 2013-02-28
x = d.getMonth(); // what to do, what to do, 3 days past 2013-02-28 is in March
// so, expect x to be March, which is 2


This is only an issue when the day value of d is greater than the maximum number of days in the month passed to setMonth(). Otherwise, it works as you'd expect.


[#80443] Friday, February 1, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaelynncherokeeg

Total Points: 697
Total Questions: 109
Total Answers: 104

Location: France
Member since Thu, Mar 18, 2021
3 Years ago
jaelynncherokeeg questions
Thu, May 27, 21, 00:00, 3 Years ago
Fri, Jan 24, 20, 00:00, 4 Years ago
Thu, Nov 14, 19, 00:00, 5 Years ago
Wed, Sep 18, 19, 00:00, 5 Years ago
;