小智 564
// 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
Run Code Online (Sandbox Code Playgroud)
ken*_*bec 112
Date.prototype.monthDays= function(){
var d= new Date(this.getFullYear(), this.getMonth()+1, 0);
return d.getDate();
}
Run Code Online (Sandbox Code Playgroud)
Cha*_*ana 34
以下内容采用任何有效的日期时间值并返回相关月份中的天数...它消除了其他答案的模糊性...
// pass in any date as parameter anyDateInMonth
function daysInMonth(anyDateInMonth) {
return new Date(anyDateInMonth.getFullYear(),
anyDateInMonth.getMonth()+1,
0).getDate();}
Run Code Online (Sandbox Code Playgroud)
另一种可能的选择是使用Datejs
那你可以做
Date.getDaysInMonth(2009, 9)
Run Code Online (Sandbox Code Playgroud)
虽然为这个函数添加一个库是过度的,但是知道你可以使用的所有选项总是很好:)
| 归档时间: |
|
| 查看次数: |
252805 次 |
| 最近记录: |