我使用Lodash和Momentjs创建具有以下结构的JSON日期范围: {“days”:[],“months”:[]}
问题是:
对于这种方法就好像是2天但是找不到它为什么不起作用。
var startDate = moment();
var endDate = moment().add(61, 'days');
var months = [];
var range = {};
range.days = [];
range.months = [];
var currDate = startDate.clone().startOf('day');
var lastDate = endDate.clone().startOf('day');
while (currDate.add(1, 'days').diff(lastDate) < 0) {
var month = {};
month.name = currDate.clone().format('MMMM');
month.year = currDate.clone().format('YYYY');
var currentMonthDaysInTotal = moment(month.year + "-" + moment().month(currDate), "YYYY-MM").daysInMonth();
var daysIndex = 1;
while (daysIndex <= currentMonthDaysInTotal) {
var newDateForList = moment([month.year, moment().month(month.name).format('M'), daysIndex]);
if (newDateForList >= startDate && newDateForList <= endDate) {
range.days.push(newDateForList);
}
daysIndex++;
}
if (months.length === 0) {
months.push(month);
}
//regarder avec mitch
if (_.findIndex(range.months, function(o) {
return o.name !== month.name;
}) === -1) {
range.months.push(month);
}
}
console.log(range);
这是一个JSFiddle,我的代码是我正在尝试做的: https://jsfiddle.net/Keldarne/LdLc6u0t/
答案 0 :(得分:1)
这是否符合您的要求?
var startDate = moment();
var endDate = moment().add(61, 'days');
var months = [];
var range = {};
range.days = [];
range.months = [];
var currDate = startDate.clone().startOf('day');
var lastDate = endDate.clone().startOf('day');
var monthYear = undefined;
while (currDate.add(1, 'days').diff(lastDate) < 0) {
range.days.push(currDate.clone());
var month = currDate.clone().format('MMMM'),
year = currDate.clone().format('YYYY');
if( month.concat( year ) !== monthYear ){
range.months.push({
name: month,
year: year
});
}
monthYear = month.concat( year );
}
console.log(range);
&#13;