I always disliked dates in JS, but as time goes by confidence grows. It does not help that I avoid reaching for external packages unless it is really necessary.
Today I needed to generate arrays of numbers that represent days between two dates.
// Outcome needed. Inputs 2020-10-28 and 2020-11-06
const labels = [28,29,30,13,1,2,3,4,5,6];
// Solution
export const getDatesBetweenDates = (
startDate: string,
endDate: string
): number[] => {
const dates: number[] = [];
const start = new Date(startDate);
const end = new Date(endDate);
while (start <= end) {
dates.push(start.getDate());
start.setDate(start.getDate() + 1);
}
return dates;
};
I have no idea why I thought that would be hard