I am trying to generate a dataset of years, each containing an array of months, for two given dates. From a given start date, say 15.05.2010, to 03.02.2012 this set should contain {'2010': ['May', 'June', 'July' ...] ... } up to {'2012': ['January', 'February']}.
I am in a situation where I cannot use libraries, I am confined to vanilla. I can generate a set of years but I am failing to add the months. Here's what I've tried so far:
const startDate = new Date('2005-01-01');
const today = new Date();
// const difference = today.getFullYear() - startFrom.getFullYear();
const years = [];
const lastYear = today.getFullYear() - 1;
const yearsAndMonths = {};
let startFrom = startDate;
// set all the years
while (startFrom.setFullYear(startFrom.getFullYear() + 1) < today.setFullYear(lastYear)) {
years.push(startFrom.toLocaleDateString('de-AT', {
year: 'numeric',
}));
}
startFrom.setFullYear(startDate);
while (startFrom.setMonth(startFrom.getMonth() + 1) < today) {
const year = startFrom.getFullYear();
const yearIndex = yearsAndMonths.indexOf(year);
yearsAndMonths[year].push(startFrom.toLocaleDateString('de-AT', {
month: 'long'
}));
}
console.log(yearsAndMonths);
https://codepen.io/thomassemmler/pen/poLBdgR?editors=0011
I need to iterate over all years and then iterate over each month in a given year, so for each year, I need to know which months where in there.