Get all days in a month that start in a certain day of the week

by Génesis García Morilla

JavaScript

/**
  * Returns all days in a month that start in a certain day of the week
  * i.e: all Mondays from July
  *
  * @param weekday Day of the week, 0 Sunday, 1 Monday, ...
  * @param month 1 January, 2 February
  * @returns days [] Array con los días
  */
function get_days_from_weekday_and_month(weekday, month) {
  let d = new Date()
  let days = []

  if (weekday < 0 || weekday > 6) return 'Weekday must be between 0 and 6'
  if (month < 1 || month > 12) return 'Month must be between 1 and 12'

  d.setMonth(month - 1)
  d.setDate(1)

  // First day on our weekday in the month
  while (d.getDay() != weekday)
    d.setDate(d.getDate() + 1)

  // Next days on our weekday in the month
  while (d.getMonth() == month - 1) {
    days.push(d.getDate())
    d.setDate(d.getDate() + 7)
  }

  return days
}

// All Saturday(6) from September(9)
document.querySelector('body').textContent = get_days_from_weekday_and_month(6, 9)