0

I found it when i set month

  1. Today is 08-31
  2. If i increase month, then today will be 09-30
  3. But it return 10-01
  4. If i decrease month, then it returns 09-01

date = new Date()
console.log( date )
// Fri Aug 31 2018 11: 28: 47 GMT + 0900(한국 표준시)

console.log( date.getMonth() ) 
// 7

console.log( date.setMonth(date.getMonth() + 1) )
// 1538360927857

console.log( date.toISOString() )
// "2018-10-01T02:28:47.857Z"

console.log( date.setMonth(date.getMonth() - 1) )
//1535768927857

console.log( date.toISOString() )
//"2018-09-01T02:28:47.857Z"

Can anyone explain me why it happens?

vol7ron
  • 40,809
  • 21
  • 119
  • 172
stories2
  • 466
  • 1
  • 5
  • 20

3 Answers3

4

When the current date is 08-31, it is not entirely clear what is should mean to set the month to 9 because 09-31 is an invalid date. That's why at some time someone had to define what setMonth should do in such situations. It seems that the defined behavior differs from the one you expect (you expected the date to become 09-30).

MDN (for setMonth) has some information about this:

The current day of month will have an impact on the behaviour of this method. Conceptually it will add the number of days given by the current day of the month to the 1st day of the new month specified as the parameter, to return the new date.

It also refers to the actual specification which gives the exact algorithm which is used to calculate the result. The reasons for the specification being as it is now are manifold, usually simplicity of the algorithm as well as the behavior on non-edge-cases are important factors.

Hero Wanders
  • 3,237
  • 1
  • 10
  • 14
2

A good explanation can be find on MDN

The current day of month will have an impact on the behaviour of this method. Conceptually it will add the number of days given by the current day of the month to the 1st day of the new month specified as the parameter, to return the new date. For example, if the current value is 31st August 2016, calling setMonth with a value of 1 will return 2nd March 2016. This is because in 2016 February had 29 days.

In your case setting setMonth(getMonth()+1) will return October 1st because September has only 30 days. Then, when you tries to decrease month to one you back to September 1st.

Vasyl Moskalov
  • 4,242
  • 3
  • 20
  • 28
-1

Javascript Date object - monthIndex is Zero (0) based, just like arrays(zero indexed).

MDN

SubSul
  • 2,523
  • 1
  • 17
  • 27