JS - 获取开始日期和结束日期之间的时间段

天数时间段:

// 映射日期格式 结果为: YYYY-MM-DD
function customFormat(date) {
    let str = "";
    let month = date.getMonth() + 1;
    let day = date.getDate();
    str += date.getFullYear().toString() + "-";
    str += month.toString().padStart(2, '0') + "-";
    str += day.toString().padStart(2, '0');
    return str;
}

function getDateBetWeen(startDate, endDate) { // 参数日期格式: YYYY-MM-DD
    if (!startDate || !endDate) return [];
    let result = [],
        startList = startDate.split('-'),
        ndList = endDate.split('-'),
        date1 = new Date(),
        date2 = new Date(),
        date1Time,
        date2Time;
    date1.setUTCFullYear(startList[0], startList[1] - 1, startList[2]);
    date2.setUTCFullYear(endList[0], endList[1] - 1, endList[2]);
    date1Time = date1.getTime();
    date2Time = date2.getTime();
    for(let time = date1Time; time <= date2Time;){
        console.log(moment(time).format('YYYY-MM-DD'));
        result.push(customFormat(new Date(parseInt(time.toString()))));
        // 如果项目使用了 moment.js,无需使用 customFormat 方法
        // result.push(moment(time).format('YYYY-MM-DD'));
        time = time + 24 * 60 * 60 * 1000;
    }
}

月数时间段:

function getMonthAll(startMonth, endMonth) { // 参数日期格式:YYYY-MM
    if (!startMonth || !endMonth) return [];

    let result = [],
        startList = startMonth.split("-"),
        endList = endMonth.split("-"),
        mCount = 0;

    // 计算开始日期、结束日期之间的月数
    if (parseInt(startList[0]) < parseInt(endList[0])) {    // 非同一年
        mCount = (parseInt(endList[0]) - parseInt(startList[0])) * 12 + parseInt(endList[1]) - parseInt(startList[1]) + 1;
    } else {
        mCount = parseInt(endList[1]) - parseInt(startList[1]) + 1;
    }
    if (mCount > 0) {
        let startY = parseInt(startList[0]);
        let startM = parseInt(startList[1]);
        for (let i = 0; i < mCount; i++) {
            result[i] = startY + "-" + startM.toString().padStart(2, '0');
            if (startM < 12) {
                startM += 1;
            } else {
                startM = 1;
                startY += 1;
            }
        }
    }

    return result;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容