js如何获取两个时间中的所有年月?

有2个时间:2016-4-12 2018-7-10 如何获取其中所有的年月?不需要精确到日

阅读 6.8k
3 个回答
function getYearAndMonth(start, end) {
    var result = [];
    var starts = start.split('-');
    var ends = end.split('-');
    var staYear = parseInt(starts[0]);
    var staMon = parseInt(starts[1]);
    var endYear = parseInt(ends[0]);
    var endMon = parseInt(ends[1]);
    while (staYear <= endYear) {
        if (staYear === endYear) {
            while (staMon < endMon) {
                staMon++;
                result.push({year: staYear, month: staMon});
            }
            staYear++;
        } else {
            staMon++;
            if (staMon > 12) {
                staMon = 1;
                staYear++;
            }
            result.push({year: staYear, month: staMon});
        }
    }

    return result;
}

由于lz从来不采纳答案,原回答删除。

新手上路,请多包涵
function getYAndM (date1, date2) {
    var starts = date1.split('-')
    var ends = date2.split('-')
    var startY = + starts[0]
    var startM = + starts[1]
    var endY =  + ends[0]
    var endM = + ends[1]
    var res = []
    if (startY == endY) {
        for (let i = startM; i< endM - 1; i++) {
            res.push({
                year: startY,
                month: i + 1
            })
        }
    } else {
        for (let i = startY; i<= endY; i++) {
            if (i == startY) {
                for(let j = startM; j < 12; j++) {
                    res.push({
                        year: i,
                        month: j + 1
                    })
                }
            } else if ( i > startY && i < endY) {
                for(let j = 0; j < 12; j++) {
                    res.push({
                        year: i,
                        month: j + 1
                    })
                }
            } else if (i == endY){
                for(let j = 1; j < endM; j++) {
                    res.push({
                        year: i,
                        month: j
                    })
                } 
            }
        } 
    }

    return res.map((v)=>{
        return `${v.year}-${v.month}`
    })
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏