Published
Edited
Jun 26, 2019
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
MinMaxDatesToArrayOfMonthStrings(minDate, maxDate)
Insert cell
Insert cell
MinMaxDatesToArrayOfMonths = (min, max) => {
function parseDate(date) {
// Assumes a Y-M-D Format
const clean = date.replace("-", " ");
const dateObject = new Date(clean);
return dateObject;
};
const parsedMin = parseDate(min)
, parsedMax = parseDate(max);
const diffTime = Math.abs(parsedMax.getTime() - parsedMin.getTime());
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
const minMonth = parsedMin.getMonth() + 1
, maxMonth = parsedMax.getMonth() + 1
const minYear = +min.split("-")[0]
, maxYear = +max.split("-")[0]
const years = diffDays / 365;
const returnArray = [];
if(years < 1) { // Less than one year
if(minYear != maxYear) { // if different years
for (let i = minMonth; i <= maxMonth + 12; i++) {
const fixYear = i > 12 ? minYear + 1 : minYear
const fixMonth = i > 12 ? i - 12 : i
returnArray.push(new Date(`${fixYear} ${fixMonth} 1`));
}
} else { // if within same year
for (let i = minMonth; i <= maxMonth; i++) {
returnArray.push(new Date(`${minYear} ${i} 1`));
}
}
} else { // More than one year
const yearToMonths = Math.floor(years) * 12
for (let i = minMonth; i <= maxMonth + yearToMonths; i++) {
const fixYear = i > 12 ? minYear + Math.floor(i / 12) : minYear;
const fixMonth = i > 12 ? i - (Math.floor(i / 12) * 12) : i;
returnArray.push(new Date(`${fixYear} ${fixMonth == 0 ? 12 : fixMonth} 1`));
}
}

return returnArray;
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more