Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Javascript, Today(31/5) add 1 month will get 1/7

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);
like image 870
Chaska Avatar asked Jan 27 '26 03:01

Chaska


1 Answers

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

like image 115
dotnetom Avatar answered Jan 28 '26 18:01

dotnetom