两种实现思路
计算出当前日期下下月日期的一号,减去1天。
e.g 2017.03.31 ---> 2017.05.01 --->2017.04.30
自己计算每月天数
判断闰年一般的规律为: 四年一闰,百年不闰,四百年再闰。
闰年判断伪代码:
(year % 4 === 0 && year % 100 !== 0)||(year % 400 === 0)
具体代码实现
/*
获取某一年份的某一月份的天数
@param {Number} year
@param {Number} month
/
function getMonthDays(year, month) {
return [31, null, 31, 30, 31][month] ||
(isLeapYear(year) ? 29 : 28);
}
var date = new Date(), year = date.getFullYear();
var nextMonth = date.getMonth() + 1, nextMonthDays = getMonthDays(year, nextMonth), nextMonthLastDate = new Date(year, nextMonth, nextMonthDays);
var afterNextMonth = date.getMonth() + 2, afterNextDate01 = new Date(year, afterNextMonth, 1), nextMonthLastDate02 = new Date(afterNextDate01.getTime() - 86400000);
console.log(nextMonthLastDate.toLocaleDateString());
console.log(nextMonthLastDate02.toLocaleDateString());