【问题标题】:Get number days in a specified month using JavaScript? [duplicate]使用 JavaScript 获取指定月份的天数? [复制]
【发布时间】:2010-11-14 03:15:11
【问题描述】:

可能重复:
What is the best way to determine the number of days in a month with javascript?

假设我将月份作为数字和年份。

【问题讨论】:

  • const d = (y, m) => new Date(y, m, 0).getDate();

标签: javascript


【解决方案1】:
// 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

【讨论】:

  • 在 Javascript 中是从 0 开始的,所以虽然这看起来是对的,但它与其他 javascript 函数不一致
  • @SamGoody,如果您对 daysInMonth 的月份输入是基于 1 的,则该函数似乎工作得很好。也就是说,例如六月 = 6。
  • 使用0作为天的意义在于它返回的是上个月的最后一天,所以在使用@时你必须在其中加上1才能返回正确的天数987654324@
  • 所以每个人都想知道为什么 new Date(2012, 5, 0).getDate() 返回 31.. 第 5 个月(基于 1)是 5 月而不是 6 月
  • 我觉得这有点混乱,所以澄清一下,以防它帮助任何人:对于 Javascript 日期函数,第二个参数是月份,从 0 开始。第三个参数是天,从 1 开始。当您将 0 传递给第三个参数时,它使用上个月的最后一天。如果您将 -1 作为第三个参数传递,则它将是上个月的倒数第二天(递减)。这就是为什么它有效的原因,但是月份必须以 1 而不是 0 开始,这与 Javascript 日期的正常情况一样,因为它实际上是切换到上个月,因为天数是 0。
【解决方案2】:

以下内容采用任何有效的日期时间值并返回相关月份中的天数……它消除了其他两个答案的歧义……

 // pass in any date as parameter anyDateInMonth
function daysInMonth(anyDateInMonth) {
    return new Date(anyDateInMonth.getFullYear(), 
                    anyDateInMonth.getMonth()+1, 
                    0).getDate();}

【讨论】:

  • 当我调用它时抛出错误:daysInMonth(new Date()).
  • 是的,只需将++anyDateInMonth.getMonth() 更改为anyDateInMonth.getMonth() + 1
  • @rescuecreative,它会像这样工作吗:++(anyDateInMonth.getMonth()) ??
  • @CharlesBretana 不,问题是您的增量运算符导致引用错误。当您使用++ 时,JavaScript 期望您使用它来增加可变值,例如存储在变量中的值。例如你不能做++5,但你可以做var x = 5; ++x。因此,在您的函数中,如果您不想使用变量,则必须实际添加 1。
  • 是的,它会持续到明年一月。
【解决方案3】:

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

那你就可以了

Date.getDaysInMonth(2009, 9)     

虽然只为这个函数添加一个库是多余的,但知道你可以使用的所有选项总是很高兴:)

【讨论】:

  • 这是他们在 Datejs 中使用的函数:return [31, ($D.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][月];
  • 什么是isLeapYear? (不是内置函数)
【解决方案4】:
Date.prototype.monthDays= function(){
    var d= new Date(this.getFullYear(), this.getMonth()+1, 0);
    return d.getDate();
}

【讨论】:

  • 据我了解,new Date(year, month, 0) 将产生上个月的最后一天,因此将+ 1 添加到参数会导致当前月份的天数。我没有在这里纠正任何事情。我正在努力确保我理解,并且我相信 kennebec 的答案是正确的答案。
  • @Brent 你理解正确。此功能还尊重基于 0 的 Javscript 月份,这既方便又方便
  • 这是正确答案,不是上面那个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-20
相关资源
最近更新 更多