Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript setMonth shows improper 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 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

like image 558
David Whitten Avatar asked Jun 01 '14 03:06

David Whitten


1 Answers

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
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));
like image 61
Aziz Saleh Avatar answered Oct 13 '22 23:10

Aziz Saleh