小智 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)

  • 在Javascript月份基于0,所以虽然这似乎是正确的,但它与其他javascript函数不一致 (45认同)
  • 我发现这有点令人困惑,所以要澄清以防万一:对于Javascript Date函数,第二个参数是month,从0开始.第三个参数是day,从1开始.当你传递0到第三个相反,它使用上个月的最后一天.如果你传递-1作为第三个参数,它将是上个月的倒数第二天(它递减).这就是为什么这样做的原因,但月份必须从1开始,而不是像Javascript日期一样正常,因为它实际上是切换到上个月,因为日期编号是0. (28认同)
  • 使用"0"作为日期的重点是它返回上个月的最后一天,因此当使用`month = new Date()时,你必须向它添加"1"以返回正确的天数.getMonth ()` (13认同)
  • @SamGoody,如果您对daysInMonth的月份输入是基于1的,那么该函数似乎工作正常.也就是说,例如June = 6. (12认同)
  • 除了它不起作用.new Date(2012,5,0).getDate()返回31.六月只有30天.同上一堆其他月份.http://jsfiddle.net/LVLd3/与http://www.timeanddate.com/calendar/上的正确日历对比 (7认同)
  • 所以每个人都在想为什么新的Date(2012,5,0).getDate()返回31 ..第5个月(1个基础)是可能而不是6月 (4认同)
  • 对.因此,如果您正在使用编程输入解析用户输入和soulscratch的功能,请使用我的函数. (3认同)

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)

  • 根据我的理解,"新日期(年,月,0)"将产生上个月的最后一天,因此在参数中添加"+ 1"将导致当前月份的日期.我在这里不纠正任何事情.我正在努力确保理解,我相信肯纳贝克的回答是正确的答案. (7认同)
  • 这是正确答案,而不是上述答案. (5认同)

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)

  • @CharlesBretana不,问题是你的增量运算符导致引用错误.当你使用`++`时,JavaScript期望你使用它来增加一个可变值,例如存储在变量中的值.例如,你不能做`++ 5`但你可以做`var x = 5; ++ x`.所以在你的函数中,如果你不想使用变量,你必须实际添加1. (2认同)

RYF*_*YFN 8

另一种可能的选择是使用Datejs

那你可以做

Date.getDaysInMonth(2009, 9)     
Run Code Online (Sandbox Code Playgroud)

虽然为这个函数添加一个库是过度的,但是知道你可以使用的所有选项总是很好:)

  • 这是他们在Datejs中使用的函数:return [31,($ D.isLeapYear(year)?29:28),31,30,31,30,31,31,30,31,30,31] [month]; (13认同)