问题描述
使用 moment().subtract(1, 'days').format("YYYY-MM-DD")
我可以获得从当前日期算起的最后 x 天.那么我如何获得上个月或过去三个月的所有天数..?
Using moment().subtract(1, 'days').format("YYYY-MM-DD")
i can get last x days from the current date. So how can i get all days from last month or last three months..?
推荐答案
如果我正确理解你的问题,这可以通过两个步骤来实现.首先计算标记上个月开始日期的时刻:
If I understand your question correctly, this can be achieved via two steps. First calculate the moment that marks the starting date of the prior month:
var prevMonth = moment().subtract(1, 'month').startOf('month');
var prevMonthDays = prevMonth.daysInMonth();
然后,迭代范围0...prevMonthDays
,计算该范围内每一天的日期,相对于上个月的开始prevMonth
:
Then, iterate over the range 0...prevMonthDays
, caclulating dates per day of that range, relative to the start of the previous month prevMonth
:
var prevMonthDay = prevMonth.clone().add(i, 'days').format("YYYY-MM-DD");
这样的事情应该可以满足您的要求:
Something like this should achieve what you require:
// Get moment at start date of previous month
var prevMonth = moment().subtract(1, 'month').startOf('month');
var prevMonthDays = prevMonth.daysInMonth();
// Array to collect dates of previous month
var prevMonthDates = [];
for (var i = 0; i < prevMonthDays; i++) {
// Calculate moment based on start of previous month, plus day offset
var prevMonthDay = prevMonth.clone().add(i, 'days').format("YYYY-MM-DD");
prevMonthDates.push(prevMonthDay);
}
console.log(prevMonthDates)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
希望这会有所帮助!
要计算从过去多个月到当月月初的日期列表,上面的代码可以概括如下:
To calculate the list of dates starting many month past through to the beginning of the current month, the code above can be generalized as follows:
var monthsPast = 4;
var prevMonthDays = 0;
var prevMonth = moment();
// Iterate over number of months past that we want to collect dates for
for (var i = 0; i < monthsPast; i++) {
// Calculate the moment at the start of a previous month
var prevMonthStart = moment().subtract(i + 1, 'month').startOf('month');
// Increment total range to collect dates over, and update prevMonth
// to current calculated moment which represents oldest month start
prevMonthDays += prevMonthStart.daysInMonth();
prevMonth = prevMonthStart;
}
// Array to collect dates of previous month
var prevMonthDates = [];
for (var i = 0; i < prevMonthDays; i++) {
// Calculate moment based on start of previous month, plus day offset
var prevMonthDay = prevMonth.clone().add(i, 'days').format("YYYY-MM-DD");
prevMonthDates.push(prevMonthDay);
}
console.log(prevMonthDates)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
这篇关于如何在MomentJS中获取上个月,过去三个月的天数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!