I am in need of a custom function called getDaysOfWeekDates
that can take a year, a month (ranging from 0 to 11), and the week number of each month (usually 4-5 weeks per month) as parameters, and return a list of dates containing each day of that particular week. For instance:
function getDaysOfWeekDates(year: number, month: number, weekNumber: number): Array<Date> {
//...
}
const days: Date[] = getDaysOfWeekDates(2020, 0, 2) // Second week of January 2020
console.log(days);
/**
* 2020-01-06T00:00:00.000Z
* 2020-01-07T00:00:00.000Z
* 2020-01-08T00:00:00.000Z
* 2020-01-09T00:00:00.000Z
* 2020-01-10T00:00:00.000Z
* 2020-01-11T00:00:00.000Z
* 2020-01-12T00:00:00.000Z
*/
I have already created a function named getDaysOfWeekDates2
which works similarly, but accepts a year and a week number as parameters (week relative to the year, where each year has 52-53 weeks):
function getDaysOfWeekDates2(year: number, weekNumber: number) {
const [ startDate ] = getDateRangeOfWeek(year, weekNumber);
return new Array(7).fill(null).map((e, index) => {
return new Date(
startDate.getFullYear(),
startDate.getMonth(),
startDate.getDate() + index
);
});
}
function getDateRangeOfWeek(year: number, weekNumber: number){
const date = new Date(String(year));
const numOfdaysPastSinceLastMonday = date.getDay() - 1;
date.setDate(date.getDate() - numOfdaysPastSinceLastMonday);
date.setDate(date.getDate() + (7 * (weekNumber - getWeekNumber(date))));
const rangeIsFrom = new Date(date.getFullYear() + "-" +(date.getMonth() + 1) + "-" + date.getDate());
date.setDate(date.getDate() + 6);
const rangeIsTo = new Date(date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + + date.getDate());
return [rangeIsFrom, rangeIsTo];
};
function getWeekNumber(date: Date): number {
const dateCopy = new Date(date.getTime());
dateCopy.setHours(0, 0, 0, 0);
// Thursday in current week decides the year.
dateCopy.setDate(dateCopy.getDate() + 3 - (dateCopy.getDay() + 6) % 7);
// January 4 is always in week 1.
const week1 = new Date(dateCopy.getFullYear(), 0, 4);
// Adjust to Thursday in week 1 and count number of weeks from date to week1.
return 1 + Math.round(((dateCopy.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
}
Any thoughts on how to modify getDaysOfWeekDates?
to achieve the desired functionality of getDaysOfWeekDates
? Or perhaps create it from scratch using an external library?