ITZone

The mouse trap in the Javascript Date.setMonth () function

Poor situation

Certainly JavaScript programmers are no stranger to Date, the object used to recite the day, count months, calculate the year. On a beautiful day March 29, 2019, while OT was in a fun and exciting way, I suddenly found a bug related to displaying the date on the Front-end. Okay, this function passes the parameter 1, returns Mar (March), passes the parameter 0 then returns Jan (January), while the result I want to receive is Feb (February). What is it playing ???

Gently turn on F12 and debug it to find out the reason is because Date.getMonth () function returns such an odd result.

It was 9pm, no longer believing in my sanity, so I switched to the Console tab to try and see if the result was like that? Is it because the function getMonth () in your project is already customizable? And the results are as follows (results are reproduced on the morning of March 30):

You can try it on your console to verify:

This mouse trap is so big

It turns out that after calling the function setMonth (1), date cannot be set to February (index = 1), but only 28 days will be removed (from March 30 to March 2).

Read the “Description” carefully, we can see that the setMonth () function will use the current day of the old month to set the date for the new month, if it exceeds the day of the new month, it will be added to the next month. For example, the current day is 30, 31, then setMonth (1) will definitely be calculated to March, because February is only 29 days maximum. Here, our current day is March 30, so when set to 2/2019 (with 28 days), we will be charged 2 more days to become 2/3.

Indeed, this mousetrap at least managed to trap a fat rat that was me.

Solution

From there, we draw that, to setMonth (), getMonth () is most comfortable, it is best to use on the 1st.

At that time, we can comfortably setMonth (), getMonth () at our discretion.

Wish you always read the document and code a little bug. Don’t get trapped like me.

Share the news now