FE-Interview icon indicating copy to clipboard operation
FE-Interview copied to clipboard

Day154:给定起止日期,返回中间的所有月份

Open Genzhen opened this issue 5 years ago • 2 comments

// 输入两个字符串 2018-08  2018-12
// 输出他们中间的月份 [2018-10, 2018-11]

每日一题会在下午四点在交流群集中讨论,五点小程序中更新答案 二维码加载失败可点击 小程序二维码

扫描下方二维码,收藏关注,及时获取答案以及详细解析,同时可解锁800+道前端面试题。

Genzhen avatar Oct 12 '20 07:10 Genzhen

function getMonths(times) {
    let start = new Date(times[0]), end = new Date(times[1]);
    const months = [];
    while(start <= end) {
      const month = start.getMonth() + 1;
      months.push(month);
      start.setMonth(month);
    }
    return months;
  }
  getMonths(['2018-10', '2018-11'])

qzruncode avatar Apr 15 '21 13:04 qzruncode

function getMonths(times) {
  let start = new Date(times[0] + '-1 00:00:00'), end = new Date(times[1] + '-1 00:00:00');
  const months = [];
  while (start < end) {
    if (
      start.getFullYear() === end.getFullYear()
      && end.getMonth() - start.getMonth() === 1
    ) {
      break;
    }
    const month = start.getMonth() + 1;
    start.setMonth(month);
    months.push(start.getFullYear() + '-' + (start.getMonth() + 1));
  }
  return months;
}
getMonths(['2018-9', '2018-11'])

buquan avatar Feb 08 '22 07:02 buquan