所以我有这个函数,基本上需要输入一个整数,并基于今天的日期,它回到'n'个月。因此,例如今天的日期是2012年11月20日。如果'n'= 1,那么它将返回2012年10月20日,依此类推。上个月计算
我面临的问题是万季月份在2月至5月之间,年份变量减去1。例如,如果n = 6,它应该返回2012年5月20日,而是返回到2011年5月20日。
我认为这可能是一个闰年问题,但是当我用n = 18进行测试时,它2010年5月20日归还,而不是2011年5月20日和2011年不是闰年。
有没有人知道我可以在这里做什么来避免这种情况?
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('-'));
};
您应该可以简单地使用'setMonth',它将为您调整年份。 'date.setMonth(date.getMonth() - 12)'将在12个月前。 – Shmiddty