js獲取時間段內屬於星期一的日期們

/* 獲取時間段內屬於星期一(*)的日期們
 * begin: 開始時間
 * end:結束時間
 * weekNum:星期幾 {number}
 */
 function getWeek (begin, end, weekNum){
     var dateArr = new Array();
     var stimeArr = begin.split("-");//=>["2018", "01", "01"]
     var etimeArr = end.split("-");//=>["2018", "01", "30"]
 
     var stoday = new Date();
     stoday.setUTCFullYear(stimeArr[0], stimeArr[1]-1, stimeArr[2]);
     var etoday = new Date();
     etoday.setUTCFullYear(etimeArr[0], etimeArr[1]-1, etimeArr[2]);
 
     var unixDb = stoday.getTime();//開始時間的毫秒數
     var unixDe = etoday.getTime();//結束時間的毫秒數
 
     for (var k = unixDb; k <= unixDe;) {
        let needJudgeDate = msToDate(parseInt(k)).withoutTime;
        //不加這個if判斷直接push的話就是已知時間段內的全部日期
        if (new Date(needJudgeDate).getDay() === weekNum) {
            dateArr.push(needJudgeDate);
        }
         k = k + 24*60*60*1000;
     }
     return dateArr;
 }
 
//根據毫秒數獲取日期
function msToDate (msec) {
    let datetime = new Date(msec);
    let year = datetime.getFullYear();
    let month = datetime.getMonth();
    let date = datetime.getDate();
    let hour = datetime.getHours();
    let minute = datetime.getMinutes();
    let second = datetime.getSeconds();
 
    let result1 = year + 
                 '-' + 
                 ((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) + 
                 '-' + 
                 ((date + 1) < 10 ? '0' + date : date) + 
                 ' ' + 
                 ((hour + 1) < 10 ? '0' + hour : hour) +
                 ':' + 
                 ((minute + 1) < 10 ? '0' + minute : minute) + 
                 ':' + 
                 ((second + 1) < 10 ? '0' + second : second);
 
    let result2 = year + 
                 '-' + 
                 ((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) + 
                 '-' + 
                 ((date + 1) < 11 ? '0' + date : date);
 
    let result = {
        hasTime: result1,
        withoutTime: result2
    };
 
    return result;
}
相關文章
相關標籤/搜索