随_声 2021-07-14 11:41 采纳率: 57.1%
浏览 299
已采纳

js循环输出从指定日期到当前日期的年月日

循环输出出从指定日期到当前日期的年月,比如指定日期是2020-09,循环出来存入数组中应该是

monthlist:[
  {year:'2020',month:'9'},
  {year:'2020',month:'10'},
  {year:'2020',month:'11'},
  {year:'2020',month:'12'},
  {year:'2021',month:'1'},
  {year:'2021',month:'2'},
  {year:'2021',month:'3'},
  {year:'2021',month:'4'},
  {year:'2021',month:'5'},
  {year:'2021',month:'6'},
  {year:'2021',month:'7'}
],

请问如何循环出来

  • 写回答

1条回答 默认 最新

  • Aganstrong 2021-07-14 12:44
    关注
    function gen(date) {
        var date = new Date(date);
        var nt = new Date().getTime();
        var monthlist = [];
        var m = date.getMonth() + 1;
        for (var i = date.getTime(); i <= nt;) {
            var d = new Date(i);
            var year = d.getFullYear();
            var month = d.getMonth() + 1;
            i += 24 * 60 * 60 * 1000;
            if (month == m) {
                continue;
            }
            m = month;
            var obj = {
                year: year,
                month: month
            }
            monthlist.push(obj);
        }
        return monthlist;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 已采纳回答 7月14日
  • 创建了问题 7月14日