js日期操作问题--给定时间区间生成区间内详细数组

给定开始/结束月份,如何生成这个时间区间内的详细月份数组

菜鸟求大佬解答,很着急

`

  var startTime = "2020-11";
  var endTime = "2021-02";
  
   已知起/终月份,如何得到瞎下面这个数据
   
  arr = ["2020-11", "2020-12", "2021-01", "2021-02"];
  

`

阅读 4.6k
5 个回答
function zeroPrefix(val) {
    return (val + '').padStart(2, '0');
}

function getTimeInterval() {
    const [startYear, startMonth] = startTime.split('-');
    const [endYear, endMonth] = endTime.split('-');
    const startTimestamp = new Date(startYear, startMonth - 1).getTime();
    const endTimestamp = new Date(endYear, endMonth - 1).getTime();
    const intervals = [];
    let timestamp = startTimestamp;
    
    while (timestamp <= endTimestamp) {
        const now = new Date(timestamp);
        const year = now.getFullYear();
        const month = now.getMonth() + 1;
        
        intervals.push(`${year}-${zeroPrefix(month)}`);
        timestamp = new Date(year, month).getTime();
    }
    
    return intervals;
}

先给一个看起来好看一点的

const getMonthes = (() => {
    function toInteger(date) {
        const [y, m] = date.split("-").map(s => parseInt(s));
        return y * 12 + m;
    }

    return function (start, end) {
        const iStart = toInteger(start);
        const iEnd = toInteger(end);
        return Array
            .from(Array(iEnd - iStart + 1), (_, i) => i + iStart)
            .map(n => `${Math.floor(n / 12)}-${((n - 1) % 12 + 1).toString().padStart(2, "0")}`);
    };
})();

再给一个通俗一点的(算法都一样):

function getMonthes2(start, end) {
    const sa = start.split("-").map(s => parseInt(s));
    const iStart = sa[0] * 12 + sa[1];
    const ea = end.split("-").map(s => parseInt(s));
    const iEnd = ea[0] * 12 + ea[1];
    const result = Array(iEnd - iStart + 1);
    for (let i = iStart; i <= iEnd; i++) {
        const year = Math.floor(i / 12);
        const month = (i - 1) % 12 + 1;
        result[i - iStart] = `${year}-${month.toString().padStart(2, "0")}`;
    }
    return result;
}

而且下面这个的效率,大概是上面那个的 2 倍。

测试:

[getMonthes, getMonthes2]
    .forEach((fn, i) => console.log(i, fn("2020-11", "2021-02")));

输出

0 [ '2020-11', '2021-12', '2021-01', '2021-02' ]
1 [ '2020-11', '2021-12', '2021-01', '2021-02' ]

const startTime = '2020-11'.split('-');

const endTime = '2021-02'.split('-');
const a = moment(startTime);
const b = moment(endTime);
const timeSlot = b.diff(a, 'months');
const resultArr = ['2020-11'];
for (let i = 1; i <= timeSlot; i+=1) {
  resultArr.push(moment('2020-11').add(i,'months').format('YYYY-MM'))
}
let startTime = "2020-11";
let endTime = "2021-02";
let arrLen = Math.trunc( (Date.parse(endTime) - Date.parse(startTime)) / 86400e3 )
let arr = Array.from({length: arrLen + 1}, (v, i) => {
  return new Date(Date.parse(startTime) + i * 86400e3).toISOString().substr(0, 7)
})
const res = [...new Set(arr)]
console.log( res )

image

// 将一段日期传换成月纬度聚合
const getMonthBetween = function(start, end) {
    let startDate = new Date(start);
    let endDate = new Date(end);
    let min = new Date();
    let max = new Date();
    min.setFullYear(startDate.getFullYear(), startDate.getMonth());
    max.setFullYear(endDate.getFullYear(), endDate.getMonth());
    let result = [];
    let curr = new Date(min);
    let index = 0;
    let length = 0;
    while (curr <= max) {
        let sum = 0;
        let curArr = [];
        if (min.getTime() === max.getTime()) {
            length = endDate.getDate() - startDate.getDate() + 1;
        } else if (curr.getTime() === min.getTime()) {
            let nowDate = startDate.getDate();
            length = new Date(startDate.getFullYear(), startDate.getMonth() + 1, 0).getDate() - nowDate + 1;
        } else if (curr.getTime() === max.getTime()) {
            length = endDate.getDate();
        } else {
            length = new Date(curr.getFullYear(), curr.getMonth() + 1, 0).getDate();
        }
        index = index + length;
        const month = curr.getMonth();
        const str = curr.toISOString().substr(0, 7);
        result.push(str);
        curr.setMonth(month + 1);
    }
    return result;
};
console.log(getMonthBetween("2020-11", "2021-02"))
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题