3

Today I just found that if I add 1 month on today's date, it returns 1/7.

Can anyone give help on this? Thank you very much.

Notice: I didn't assign the date to today because today is 31/5, and some of you guys is still on 30/5

var today = new Date(); // today is 31/5 in my timezone
console.log(today);
today.setMonth(today.getMonth() + 1);
console.log(today);
Chaska
  • 3,165
  • 1
  • 11
  • 17
  • adding a month results in `"2019-06-31T03:43:45.819Z"` which is not possible. So, it's changed to `"2019-07-01T03:43:45.819Z"` – Arif Hosan May 31 '19 at 03:45
  • there is no 31 in June? – Zhubei Federer May 31 '19 at 03:46
  • This question has been asked [*many times before*](https://stackoverflow.com/search?q=%5Bjavascript%5D+add+month+to+a+date). Try [*this answer*](https://stackoverflow.com/a/24361931/257182), or [*this one*](https://stackoverflow.com/a/36428762/257182). – RobG May 31 '19 at 04:35

1 Answers1

3

This is a weird way how dates work in JavaScript. According to documentation in 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 when you add a month to 31st of May you get 31st of June. This is not a valid date, and JavaScript translates it to 1st of July

dotnetom
  • 24,551
  • 9
  • 51
  • 54