Javascript setMonth shows wrong date

If I have a date of May 31, 2014, then if I say date.setMonth (date.getMonth () + 1) to get to the next month, I get July 1, 2014. I expected to receive June 30, 2014. I think because there are no 31 days in June, so JavaScript is better to avoid errors.

I wrote a special function to execute the setDate, setMonth, and setYear functions on this calculation-based date object. It seems that setMonth is not doing anything suitable.

Ideas

David

+6
source share
1 answer

Are you trying to get 1 month from now? If so, what you get is right. 1 Month from May 31 - July 1, and not June 30. If you want it to go only to the second month only depending on the number of days in that month:

Example: Jan 31st 2014 -> Feb 28th 2014 or the case you mentioned, you can use a little hack to use minus the current days and the number of days in the next month to keep you in the same month:

 // Assume its yesterday var date = new Date(2014, 4, 31); // Get the current date var currentDate = date.getDate(); // Set to day 1 to avoid forward date.setDate(1); // Increase month by 1 date.setMonth(date.getMonth() + 1); // Get max # of days in this new month var daysInMonth = new Date(date.getYear(), date.getMonth()+1, 0).getDate(); // Set the date to the minimum of current date of days in month date.setDate(Math.min(currentDate, daysInMonth)); 
+6
source

Source: https://habr.com/ru/post/970136/


All Articles