Inspired by a PHP version of this found here, here is a Javascript function that takes the number of the month (0-11) and the year and returns the Date object of the first Monday in that month. I find it useful for determining weeks in the month.
// get first Monday of the month, useful for determining week durations // @param - integer: month - which month // @param - integer: year - which year function firstMonday (month, year){ var d = new Date(year, month, 1, 0, 0, 0, 0) var day = 0 // check if first of the month is a Sunday, if so set date to the second if (d.getDay() == 0) { day = 2 d = d.setDate(day) d = new Date(d) } // check if first of the month is a Monday, if so return the date, otherwise get to the Monday following the first of the month else if (d.getDay() != 1) { day = 9-(d.getDay()) d = d.setDate(day) d = new Date(d) } return d }
Please let me know if you find it useful. Enjoy!
function firstMonday(month, year) { var d = new Date(year, month, 1, 0, 0, 0, 0) var day = 0 if (d.getDay() == 0) { day = 2 d = d.setDate(day) d = new Date(d) } else if (d.getDay() != 1) { day = 9-(d.getDay()) d = d.setDate(day) d = new Date(d) } return d.toString() } firstMonday(10, 2011)