JavaScript(JS)计算某年某月的天数(月末)

方法1

/**
 * 获取某年月的天数
 * @param year 年
 * @param month 月(0-11)
 * @returns {number} 天数
 */
var getDaysOfMonth = function (year, month) {
    month = month + 1;
    switch (month) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            return 31;
        case 4:
        case 6:
        case 9:
        case 11:
            return 30;
        case 2:
            return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) ? 29 : 28;
        default:
            return 0;
    }
};

方法2

/**
 * 获取某年月的天数
 * @param year 年
 * @param month 月(0-11)
 * @returns {number} 天数
 */
var getDaysOfMonth2 = function (year, month) {
    month++;
    if (month > 11) {
        month = 0, year++;
    }
    return new Date(new Date(year, month, 1).getTime() - 1000 * 3600 * 24).getDate();
};

经过测试第一个方法效率明显高出不少。

测试代码

var testCostTime = function (method) {
             var d1 = new Date();
             if(method==1){
                 for(var i=0;i<100000;i++){
                     getDaysOfMonth(2017,1);
                 }
             }else{
                 for(var i=0;i<100000;i++){
                     getDaysOfMonth2(2017,1);
                 }
             }
             console.log('cost time:'+(new Date().getTime()-d1.getTime()));
         }
<input type="button" value="测试1" onclick="testCostTime(1)"/>
 <input type="button" value="测试2" onclick="testCostTime(2)"/>

进行10万次调用测试后,方法1耗时为0-1毫秒,方法2耗时为38-41毫秒。所以建议使用方法一,进行计算年月的天数。

原文地址:https://www.cnblogs.com/hdwang/p/7339351.html