Am just coding sth where I have to give out the count of weeks in every month of the year, so I need a function with a year- and a month-parameter to give out the amount of weeks in this month as a int.
like function getcalweeks(year, month) { xyz }
where the output is just a variable that gives out the count of weeks in this month.
for example: function getcalweeks(2021, 1) { xyz }
should return 4
.
I looked through the web but just found some codes that wouldnt work, in the best one I found there were just 50 calendar weeks, not 52. (btw am in germany).
the code:
function getWeeksInMonth(year, month) {
const weeks = [],
firstDate = new Date(year, month, 1),
lastDate = new Date(year, month + 1, 0),
numDays = lastDate.getDate();
let dayOfWeekCounter = firstDate.getDay();
for (let date = 1; date <= numDays; date++) {
if (dayOfWeekCounter === 0 || weeks.length === 0) {
weeks.push([]);
}
weeks[weeks.length - 1].push(date);
dayOfWeekCounter = (dayOfWeekCounter + 1) % 7;
}
return weeks
.filter((w) => !!w.length)
.map((w) => ({
start: w[0],
end: w[w.length - 1],
dates: w,
}));
}
If somebody could help me I would be really thankful for that.
best regards,
silliton