1. 程式人生 > >js計算一個月多少天

js計算一個月多少天

var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
 var date = now.getDate();

function getDates(ok){


switch(month){
case 4:;
case 6:;
case 9:;
case 11:return 30;break;
case 2:return (year%4==0)&&(year%100!=0||year%400==0)?29:28;break;//判斷閏年
default:return 31;
}

}

下面為網上搜的比較簡單

//一個月有多少天  
function getDates(){
    var curDate = new Date();
    /* 獲取當前月份 */
    var curMonth = curDate.getMonth();
    /*  生成實際的月份: 由於curMonth會比實際月份小1, 故需加1 */
    curDate.setMonth(curMonth + 1);
    /* 將日期設定為0, 這裡為什麼要這樣設定, 我不知道原因, 這是從網上學來的 */
    curDate.setDate(0);
    /* 返回當月的天數 */
    return curDate.getDate();
}