Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`date.setMonth` causes the month to be set too high if `date` is at the end of the month

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.

like image 541
willian绿茶 Avatar asked Feb 04 '13 04:02

willian绿茶


People also ask

What type of method is setMonth?

Definition and Usage. The setMonth() method sets the month of a date object. Note: January is 0, February is 1, and so on. This method can also be used to set the day of the month.

What is the difference between Get month and set month?

Description. If you do not specify the dayValue parameter, the value returned from the getDate() method is used. If a parameter you specify is outside of the expected range, setMonth() attempts to update the date information in the Date object accordingly.


1 Answers

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.

like image 150
hrunting Avatar answered Oct 09 '22 01:10

hrunting