【发布时间】: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
可能重复:
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
// 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
【讨论】:
0作为天的意义在于它返回的是上个月的最后一天,所以在使用@时你必须在其中加上1才能返回正确的天数987654324@
以下内容采用任何有效的日期时间值并返回相关月份中的天数……它消除了其他两个答案的歧义……
// pass in any date as parameter anyDateInMonth
function daysInMonth(anyDateInMonth) {
return new Date(anyDateInMonth.getFullYear(),
anyDateInMonth.getMonth()+1,
0).getDate();}
【讨论】:
++anyDateInMonth.getMonth() 更改为anyDateInMonth.getMonth() + 1
++(anyDateInMonth.getMonth()) ??
++ 时,JavaScript 期望您使用它来增加可变值,例如存储在变量中的值。例如你不能做++5,但你可以做var x = 5; ++x。因此,在您的函数中,如果您不想使用变量,则必须实际添加 1。
【讨论】:
isLeapYear? (不是内置函数)
Date.prototype.monthDays= function(){
var d= new Date(this.getFullYear(), this.getMonth()+1, 0);
return d.getDate();
}
【讨论】:
new Date(year, month, 0) 将产生上个月的最后一天,因此将+ 1 添加到参数会导致当前月份的天数。我没有在这里纠正任何事情。我正在努力确保我理解,并且我相信 kennebec 的答案是正确的答案。