Get Weeks In Month Through Javascript

后端 未结 17 1329
盖世英雄少女心
盖世英雄少女心 2020-11-30 09:03

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

17条回答
  •  抹茶落季
    2020-11-30 09:35

    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);
    }

提交回复
热议问题