【问题标题】:How to get a list of all months from current month to a month in the past using moment.js如何使用moment.js获取从当前月份到过去一个月的所有月份列表
【发布时间】:2020-05-30 07:03:14
【问题描述】:

我正在尝试使用 moment.js 生成从 2020 年 4 月到过去一个月(2019 年 10 月)的月份列表。

const start = moment().startOf('month')
const startMonth = moment('10-01-2019', 'MM-DD-YYYY').format('MMMM YYYY')
const month = moment().startOf('month').format('MM')
for (let i = 0; i < month; i++) {
  const m = start.subtract(1, 'month').format('MMMM YYYY')
  if (m === startMonth) {
    break;
  }
  console.log(m)
}
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js" integrity="sha256-5oApc/wMda1ntIEK4qoWJ4YItnV4fBHMwywunj8gPqc=" crossorigin="anonymous"&gt;&lt;/script&gt;

结果我只有 5 个月的时间。有人可以帮忙吗?

【问题讨论】:

    标签: javascript ecmascript-6 momentjs


    【解决方案1】:

    使用isSameOrBefore()

    const start = moment().startOf('month')
    const end = moment('11-11-2019', 'MM-DD-YYYY')
    
    while (end.isSameOrBefore(start, 'month')) {
      console.log(start.format('MMMM YYYY'))
      start.subtract(1, 'month')
    }
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js" integrity="sha256-5oApc/wMda1ntIEK4qoWJ4YItnV4fBHMwywunj8gPqc=" crossorigin="anonymous"&gt;&lt;/script&gt;

    排除当前月份

    const start = moment().startOf('month')
    const end = moment('11-11-2019', 'MM-DD-YYYY')
    
    while (end.isBefore(start, 'month')) {
      start.subtract(1, 'month')
      console.log(start.format('MMMM YYYY'))
    }
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js" integrity="sha256-5oApc/wMda1ntIEK4qoWJ4YItnV4fBHMwywunj8gPqc=" crossorigin="anonymous"&gt;&lt;/script&gt;

    【讨论】:

    • 哇!那非常整洁。如何排除当前月份?
    【解决方案2】:

    这样的?

    const start = moment().startOf('month')
    const end = moment('10-01-2018', 'MM-DD-YYYY')
    
    let results = []
    let current = start
    while (current.format('MMMM YYYY') !== end.format('MMMM YYYY')) {
      results.push(current.format('MMMM YYYY'))
      current = current.subtract(1, 'month')
    }
    // need to add current one last time because the loop will have ended when it is equal to the end date, and will not have added it
    results.push(current.format('MMMM YYYY'))
    
    console.log(results)
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js" integrity="sha256-5oApc/wMda1ntIEK4qoWJ4YItnV4fBHMwywunj8gPqc=" crossorigin="anonymous"&gt;&lt;/script&gt;

    【讨论】:

    • 哇!在这种情况下如何排除当前月份?
    • 提前一个月开始:const start = moment().subtract(1, 'month').startOf('month')
    • 太棒了!就是这样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    • 2013-01-29
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多