JavaScript:根据当前日期,获取下月最后一天的日期

前端之家收集整理的这篇文章主要介绍了JavaScript:根据当前日期,获取下月最后一天的日期前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

两种实现思路

计算出当前日期下下月日期的一号,减去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());

猜你在找的JavaScript相关文章