根據當前時間動態獲取上一個月的時間及獲取當月的最後一天

業務需求中,經常會根據當前時間獲取上一個月的時間或者當月的最後一天,由於每個月的天數都不同,爲了考慮時間上的準確性我們需要做一些判斷和計算,具體方法如下:

/* 獲取上一個月時間,返回yyyy-MM-dd字符串
* getLastMonthTime('2020-04-16','date'); date類型
* getLastMonthTime(new Date,'num'); //時間戳類型
* */
function getLastMonthTime(date, type){
    var daysInMonth = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    if(type == 'date'){ //時間戳格式
        date = new Date(date);
    }
    var strYear = date.getFullYear();
    var strDay = date.getDate();
    var strMonth = date.getMonth()+1;
    //判斷二月份天數
    if (((strYear % 4) === 0) && ((strYear % 100)!==0) || ((strYear % 400)===0)){
        daysInMonth[2] = 29;
    }
    //判斷跨年
    if(strMonth - 1 === 0){
        strYear -= 1;
        strMonth = 12;
    }else{
        strMonth -= 1;
    }
    strDay = Math.min(strDay,daysInMonth[strMonth]);
    strMonth = strMonth<10?"0"+strMonth:strMonth;
    strDay = strDay<10?"0"+strDay:strDay;
    return strYear+"-"+strMonth+"-"+strDay;
}

/* 獲取每月的最後一天
 * date類型爲(yyyy-MM-dd HH:mm:ss、yyyy-MM-dd HH:mm、yyyy-MM-dd HH、yyyy-MM-dd 、yyyy-MM)
 *  */
function getLastDay(date) {
    var dateMonth  = date.substr(5,2);
    var month = ['01','02','03','04','05','06','07','08','09','10','11','12'];
    var daysInMonth = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    var fullYear = new Date(date).getFullYear();
    //判斷二月份天數
    if (fullYear % 4 == 0 && (fullYear % 100 != 0 || fullYear % 400 == 0)){
        daysInMonth[1] = 29;
    }
    var lastDay = daysInMonth[month.indexOf(dateMonth)];
    return lastDay;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章