[英]How to get a list of all months from current month to a month in the past 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>
結果我只有5個月。 有人可以幫忙嗎?
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>
排除當月
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>
像這樣的東西?
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.