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 01, 2014. I would expect to get June 30, 2014. I guess it's because June doesn't have 31 days so JavaScript does it best to avoid errors.
I wrote a special function to actually do the setDate, setMonth and setYear functions on that date object based on calculations. Seems like the setMonth alone doesnt do the right thing.
Ideas,
David
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 01, 2014. I would expect to get June 30, 2014. I guess it's because June doesn't have 31 days so JavaScript does it best to avoid errors.
I wrote a special function to actually do the setDate, setMonth and setYear functions on that date object based on calculations. Seems like the setMonth alone doesnt do the right thing.
Ideas,
David
Share Improve this question asked Jun 1, 2014 at 3:29 David WhittenDavid Whitten 5731 gold badge4 silver badges12 bronze badges 3 |2 Answers
Reset to default 12Are 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
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));
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. Reference:
Add months/days/etc: https://momentjs.com/docs/#/manipulating/add/
Substract months/days/etc: https://momentjs.com/docs/#/manipulating/subtract/
Date.prototype.setMonth
, you'll see that it takes a second parameter,dayValue
. If you don't specify this, it usesDate.prototype.getDate
, which will return31
for May 31st. Obviously, if you're setting to June, but it gets the value of31
for thedayValue
, then it is stuck in a bad place since June doesn't have 31 days. – ajp15243 Commented Jun 1, 2014 at 3:47