Javascript setMonth shows improper date

Javascript setMonth shows improper date

Are you trying to get 1 month from now? If so, what you are getting is correct. 1 Month from May 31 is July 1, not June 30. If you want it to only move to the second month only depending on the number of days in this month:

Ex: Jan 31st 2014 -> Feb 28th 2014
or the case you mentioned, you can use a small hack to use the min of the current days and the number of days in the next month to keep you in that 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
// 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));

I just had this same issue, I assumed JS Date handled the number of days for me when I changed the month number. I ended up using moment instead.

Add months/days/etc:

Substract months/days/etc:

Javascript setMonth shows improper date

Leave a Reply

Your email address will not be published. Required fields are marked *