用时刻生成月份数组 - Reactjs
Generate Array of months with moment - Reactjs
我的目标是生成一个从今天到过去 1 年的月份数组。所以它看起来像这样
(基于今天日期 04-05-2022)
const months = ['Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr','May']
我目前尝试生成我的数组:
useEffect(() => {
const months = []
const dateStart = moment()
const dateEnd = moment().subtract(11, 'month')
while (dateEnd.diff(dateStart, 'months') >= 0) {
months.push(dateStart.format('MMM'))
dateStart.add(1, 'month')
}
console.log(months)
return months
},[])
通常我认为它必须没问题,但在我的输出中我得到一个空数组。有人知道我做错了什么吗?感谢您的帮助。
而不是使用 diff()
,为什么不使用 isBefore()
此外,您要向 dateStart
添加 1 个月,但这需要 dateEnd
const months = []
const dateStart = moment()
const dateEnd = moment().subtract(11, 'month')
while (dateEnd.isBefore(dateStart, 'day')) {
months.push(dateEnd.format('MMM'))
dateEnd.add(1, 'month')
}
months.push(dateEnd.format('MMM'))
console.log(months);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.3/moment.min.js"></script>
[
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
"Jan",
"Feb",
"Mar",
"Apr",
"May"
]
我的目标是生成一个从今天到过去 1 年的月份数组。所以它看起来像这样
(基于今天日期 04-05-2022)
const months = ['Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr','May']
我目前尝试生成我的数组:
useEffect(() => {
const months = []
const dateStart = moment()
const dateEnd = moment().subtract(11, 'month')
while (dateEnd.diff(dateStart, 'months') >= 0) {
months.push(dateStart.format('MMM'))
dateStart.add(1, 'month')
}
console.log(months)
return months
},[])
通常我认为它必须没问题,但在我的输出中我得到一个空数组。有人知道我做错了什么吗?感谢您的帮助。
而不是使用 diff()
,为什么不使用 isBefore()
此外,您要向 dateStart
添加 1 个月,但这需要 dateEnd
const months = []
const dateStart = moment()
const dateEnd = moment().subtract(11, 'month')
while (dateEnd.isBefore(dateStart, 'day')) {
months.push(dateEnd.format('MMM'))
dateEnd.add(1, 'month')
}
months.push(dateEnd.format('MMM'))
console.log(months);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.3/moment.min.js"></script>
[
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
"Jan",
"Feb",
"Mar",
"Apr",
"May"
]