第一种方法:
function getLastDay(year,month) { var new_year = year; //取当前的年份 var new_month = month++;//取下一个月的第一天,方便计算(最后一天不固定) if(month>12) //如果当前大于12月,则年份转到下一年 { new_month -=12; //月份减 new_year++; //年份增 } var new_date = new Date(new_year,new_month,1); //取当年当月中的第一天 var date_count = (new Date(new_date.getTime()-1000*60*60*24)).getDate();//获取当月的天数 var last_date = new Date(new_date.getTime()-1000*60*60*24);//获得当月最后一天的日期 return date_count; }
<input id="Button1" type="button" value="取2007年5月的最后一天" onClick="alert(getLastDay(2007,5))" />
第二种方法:
// 计算下个月一号到这个月一号的时间戳的差值 ,然后计算出有几天 function getCountDays(){ var date = new Date(), month = date.getMonth(), newday = date.setDate(1), // 设置当前时间为这个月一号 nowMonthTime = date.getTime(), // 获取这个月的一号的时间戳 nextMonth = date.setMonth(month + 1), // 设置当前时间为下个月一号 nextMonthTime = date.getTime(), // 获取下个月的一号的时间戳 countDays = (nextMonthTime - nowMonthTime)/24/60/60/1000, // 返回这个月的天数 lastDayDate = new Date((new Date()).setDate(countDays)); // 返回这个月的最后一天的日期 return {countDays, lastDayDate }; } var lastDay = getCountDays().lastDayDate; $(".countDay").text(getCountDays().countDays); $(".lastDayDate").text(lastDay.getFullYear() + '-' + (lastDay.getMonth() + 1) + '-' + lastDay.getDate())
<div>这个月共有几天:<span class="countDay"></span></div> <div>这个月最后一天是几号:<span class="lastDayDate"></span></div>