Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

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

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

菜鸟求大佬解答,很着急

`

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

`


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...