js获取2个时间差之间所有月份

2024年07月27日 建站教程

function getMonthBetween(start, end) {
  let result = [];
  let min = new Date(start);
  let max = new Date(end);
  let curr = min;
  while (curr <= max) {
    let month = new Date(curr).getMonth() + 1;
    let t = ""
    if (month < 10) {
      t = '0' + month
    } else t = month
    let str = curr.getFullYear() + "-" + (t);
    let s = curr.getFullYear() + "-0";
    if (str == s) {
      str = curr.getFullYear() + "-12";
    }
    result.push(str);
    curr.setMonth(month);
  }
  return result;
}

//打印
console.log(getMonthBetween('2022-01','2022-05'))

//输出结果:
['2022-1', '2022-2', '2022-3', '2022-4', '2022-5']

本文链接:http://so.lmcjl.com/news/9289/

展开阅读全文
相关内容