可能的重复: 用javascript确定一个月有多少天的最好方法是什么?
假设我有一个月份和一个年份。
可能的重复: 用javascript确定一个月有多少天的最好方法是什么?
假设我有一个月份和一个年份。
// Month in JavaScript is 0-indexed (January is 0, February is 1, etc),
// but by using 0 as the day it will give us the last day of the prior
// month. So passing in 1 as the month number will return the last day
// of January, not February
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
下面的函数接受任何有效的datetime值,并返回相关月份中的天数…它消除了其他两个答案的模糊性……
// pass in any date as parameter anyDateInMonth
function daysInMonth(anyDateInMonth) {
return new Date(anyDateInMonth.getFullYear(),
anyDateInMonth.getMonth()+1,
0).getDate();}
Date.prototype.monthDays= function(){
var d= new Date(this.getFullYear(), this.getMonth()+1, 0);
return d.getDate();
}
另一个可能的选择是使用Datejs
然后你就可以
Date.getDaysInMonth(2009, 9)
虽然仅仅为这个函数添加一个库是多余的,但知道所有可用的选项总是很好的:)