首页 > 解决方案 > 使用时刻 JS 获取两个日期之间的开始和结束月份列表

问题描述

我有 2 次这样的约会

2018-01-012019-01-01

我想返回这两个日期之间所有月份的列表,但同时获取月份的开始和列表中的结尾,如下所示

 2018-01-01 - 2018-01-31
 2018-02-01 - 2018-02-28
 2018-03-01 - 2018-03-31

依此类推,两个日期之间的所有月份。我将如何使用 Moment JS 做到这一点?

标签: javascriptmomentjs

解决方案


只是一个小的可运行样本。小心 moment.js:时刻变异!

我希望这能帮到您!

const format = 'YYYY-MM-DD';
const start = moment('2018-01-01', format), end = moment('2019-01-01', format);
const result = [];
while(start.isBefore(end)) {
  result.push({
    start: start.startOf('month').format(format), 
    end: start.endOf('month').format(format)
  });
  start.add(1, 'month');
} 

console.log(result);
<script src="https://momentjs.com/downloads/moment.min.js"></script>


推荐阅读