Reputation: 81
I use Lodash and Momentjs to create a JSON date range with this structure : {"days":[], "months": []}
Problem is :
Was like 2 days on this method but can't find why it doesn't work.
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);
Here is a JSFiddle with my code for what I'm trying to do : https://jsfiddle.net/Keldarne/LdLc6u0t/
Upvotes: 0
Views: 58
Reputation: 1123
Is this along the right lines of what you wanted?
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);
Upvotes: 1