通过JS计算一个月有多少天

// 计算当前月份有多少天


// 第一种方式
function getCountDays(){
	var curDate = new Date();
	// 获取当前月份
	var curMonth = curDate.getMonth();
	// 实际月份比curMonth大1,下面将月份设置为下一个月
	curDate.setMonth(curMonth+1);
	// 将日期设置为0,表示自动计算为上个月(这里指的是当前月份)的最后一天
	curDate.setDate(0);
	// 返回当前月份的天数
	return curDate.getDate();
}
getCountDays();


// 第二种方式
// 计算当前月份有多少天
function getCountDays(){
	var curDate = new Date();
	// 获取当前月份
	var curMonth = curDate.getMonth();
	// 将日期设置为32,表示自动计算为下个月的第几天(这取决于当前月份有多少天)
	curDate.setDate(32);
	// 返回当前月份的天数
	return 32-curDate.getDate();
}
getCountDays();

笔记:

setDate()方法

setDate()方法用来设置日期时间中的日,也就是每个月中的几号,传入参数为1~31的整数。若是传入的值超出当前月份的正常范围,setDate()方法也会依据超出的数值进行计算,比如setDate(0)会让日期变为上一个月的最后一天,setDate(-1)会让日期变为上一个月的倒数第二天,若当月有31天,那么setDate(32)会让日期变为下一个月的第一天。

猜你喜欢

转载自blog.csdn.net/u011435776/article/details/80766978