So i have this function that basically takes an input of an integer and based off of today’s date, it goes back to that ‘n’ number of months. So for example today’s date is Nov 20, 2012. If ‘n’ = 1, then it returns Oct 20, 2012 and so on.
The problem that Im facing is that everythime months is between Feb-May, the years variable is subtracted by one. So for example, If n = 6, it should return May 20, 2012. Instead it returns May 20, 2011.
I thought it could be a leap year issue but when I tested it out with n = 18, it returned May 20, 2010 instead of May 20, 2011 and 2011 is not a leap year.
Does anyone know what I can do here to avoid this?
lastNmonths = function(n) {
var date = new Date();
if (n <= 0)
console.log( [date.getFullYear(), date.getMonth() + 1 , date.getDate()].join('-'));
var years = Math.round(n / 12);
var months = n % 12;
if (years > 0)
date.setFullYear(date.getFullYear() - years);
if (months > 0) {
if (months >= date.getMonth()) {
date.setFullYear(date.getFullYear() );
months = 12 - months;
date.setMonth(date.getMonth() + months );
} else {
date.setMonth(date.getMonth() - months);
}
}
console.log( [date.getFullYear(), date.getMonth() + 1, date.getDate()].join('-'));
};
You approach is unnecessarily complicated and necessarily error-prone. Use the built-in overflow control of
Dateinstances instead: