简体   繁体   English

如何使用moment.js获取从当前月份到过去一个月的所有月份列表

[英]How to get a list of all months from current month to a month in the past using moment.js

I'm trying to generate a list of months starting from April 2020 to a month in the past ( October 2019 ) using moment.js .我正在尝试使用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) }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js" integrity="sha256-5oApc/wMda1ntIEK4qoWJ4YItnV4fBHMwywunj8gPqc=" crossorigin="anonymous"></script>

I get only 5 months as a result.结果我只有5个月。 Could anyone please help?有人可以帮忙吗?

Using isSameOrBefore()使用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') }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js" integrity="sha256-5oApc/wMda1ntIEK4qoWJ4YItnV4fBHMwywunj8gPqc=" crossorigin="anonymous"></script>

Exclude current month排除当月

 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')) }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js" integrity="sha256-5oApc/wMda1ntIEK4qoWJ4YItnV4fBHMwywunj8gPqc=" crossorigin="anonymous"></script>

Something like this?像这样的东西?

 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)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js" integrity="sha256-5oApc/wMda1ntIEK4qoWJ4YItnV4fBHMwywunj8gPqc=" crossorigin="anonymous"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM