我一直在使用这个函数,但我想知道获取它的最有效和最准确的方法是什么。
function daysInMonth(iMonth, iYear) {
return 32 - new Date(iYear, iMonth, 32).getDate();
}
最佳答案
function daysInMonth (month, year) { // Use 1 for January, 2 for February, etc.
return new Date(year, month, 0).getDate();
}
console.log(daysInMonth(2, 1999)); // February in a non-leap year.
console.log(daysInMonth(2, 2000)); // February in a leap year.
第 0 天是上个月的最后一天。因为月份构造函数是基于 0 的,所以效果很好。有点 hack,但这基本上就是您减去 32 所做的事情。
关于javascript - 使用 JavaScript 确定一个月中的天数的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/315760/