可能重复:
What is the best way to determine the number of days in a month with javascript?
假设我将月份作为数字和一年。
答案 0 :(得分:535)
// Month here is 1-indexed (January is 1, February is 2, etc). This is
// because we're using 0 as the day so that it returns the last day
// of the last month, so you have to add 1 to the month number
// so it returns the correct amount of days
function daysInMonth (month, year) {
return new Date(year, month, 0).getDate();
}
// July
daysInMonth(7,2009); // 31
// February
daysInMonth(2,2009); // 28
daysInMonth(2,2008); // 29
答案 1 :(得分:103)
Date.prototype.monthDays= function(){
var d= new Date(this.getFullYear(), this.getMonth()+1, 0);
return d.getDate();
}
答案 2 :(得分:30)
以下内容采用任何有效的日期时间值并返回相关月份中的天数...它消除了其他答案的含糊不清...
// pass in any date as parameter anyDateInMonth
function daysInMonth(anyDateInMonth) {
return new Date(anyDateInMonth.getFullYear(),
anyDateInMonth.getMonth()+1,
0).getDate();}
答案 3 :(得分:8)