js日期處理函數 -- 判斷閏年,獲取當月的總天數、添加月份


1. 判斷是否是閏年

function isLeapYear(eDate) {
    var year = eDate.getFullYear();
    return (((0 == year % 4) && (0 != (year % 100))) || (0 == year % 400));
}

2. 獲取月份的總天數

function getDaysInMonth(eDate) {
    var daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
    daysInMonth[1] = isLeapYear(eDate) ? 29 : 28;
    return daysInMonth[eDate.getMonth()];
}

3. 給日期加上幾個月(如果得到的日期沒有這一天,則自動變為當月的最后一天)

function addMonth(eDate, duration) {
    var month = eDate.getMonth() + parseInt(duration);
    var day = eDate.getDate();  
    eDate.setDate(1);  
    eDate.setMonth(month);
    var daysInMonth = getDaysInMonth(eDate);
    if(day > daysInMonth){
        day = daysInMonth;
    }
    eDate.setDate(day);
    return eDate;
}

4. 修改日期

function changeExpiryDate(expDate, duration, durationType){
    if(durationType == 2){//Day
        expDate.setDate(expDate.getDate()+parseInt(duration));
    }else if(durationType == 3){//Week
        expDate.setDate(expDate.getDate()+parseInt(duration*7));
    }else if(durationType == 4){//Month
        expDate = addMonth(expDate.getTime(), duration);
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM