In Javascript, how do I get the number of weeks in a month? I can\'t seem to find code for this anywhere.
I need this to be able to know how many rows I need for a g
ES6 variant, using consistent zero-based months index. Tested for years from 2015 to 2025.
/**
* Returns number of weeks
*
* @param {Number} year - full year (2018)
* @param {Number} month - zero-based month index (0-11)
* @param {Boolean} fromMonday - false if weeks start from Sunday, true - from Monday.
* @returns {number}
*/
const weeksInMonth = (year, month, fromMonday = false) => {
const first = new Date(year, month, 1);
const last = new Date(year, month + 1, 0);
let dayOfWeek = first.getDay();
if (fromMonday && dayOfWeek === 0) dayOfWeek = 7;
let days = dayOfWeek + last.getDate();
if (fromMonday) days -= 1;
return Math.ceil(days / 7);
}