以下是使用JavaScript获取近一年日期数组的示例代码:

function getRecentYearDates() {
  var dates = [];
  var currentDate = new Date();

  for (var i = 0; i < 365; i++) {
    var year = currentDate.getFullYear();
    var month = ("0" + (currentDate.getMonth() + 1)).slice(-2);
    var day = ("0" + currentDate.getDate()).slice(-2);
    var formattedDate = year + "-" + month;

    dates.push(formattedDate);

    currentDate.setDate(currentDate.getDate() - 1);
  }

  return dates;
}

var recentYearDates = getRecentYearDates();
console.log(recentYearDates);

此代码中,我们首先创建一个空数组dates来存储日期。然后,我们获取当前日期对象currentDate。接下来,使用一个循环来获取近一年的日期,每次迭代时,我们将当前日期的年份和月份进行格式化,并将其添加到dates数组中。在每次迭代的最后,我们通过currentDate.setDate(currentDate.getDate() - 1);将当前日期减去一天,以获取前一天的日期。最后,我们返回dates数组。

运行以上代码,将在控制台中打印出近一年的日期数组,格式为yyyy-MM

js获取近一年日期数组格式yyyy-MM

原文地址: https://www.cveoy.top/t/topic/jckG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录