使用 JavaScript 获取指定月份的天数?
IT技术
javascript
                    2021-01-22 12:07:23
                
                    
                
            
        4个回答
            // 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
Date.prototype.monthDays= function(){
    var d= new Date(this.getFullYear(), this.getMonth()+1, 0);
    return d.getDate();
}
以下采用任何有效的日期时间值并返回相关月份的天数......它消除了其他两个答案的歧义......
 // pass in any date as parameter anyDateInMonth
function daysInMonth(anyDateInMonth) {
    return new Date(anyDateInMonth.getFullYear(), 
                    anyDateInMonth.getMonth()+1, 
                    0).getDate();}
其它你可能感兴趣的问题