Clint_A
Clint_A

Reputation: 536

How can I get dates given the name of the day of the week in Javascript?

Suppose I have the name of the day of the week like 'Wednesday' or 'Monday', is there a way to get the dates of a month returned related to the given day of the week?

For instance in the given calendar below, is there a way to get the dates [2,9,16,23,30] for the day of 'Wednesday' in September 2020? The solution doesn't have to exactly match this as long as it returns the proper dates for the given day:

enter image description here

Upvotes: 1

Views: 359

Answers (1)

mplungjan
mplungjan

Reputation: 177950

Have a go with this

const dayNames = "Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday".split(","),
  days = [...Array(32).keys()].splice(1); // generate 1-31
const getDates = (yyyy, mm, dayName) => {
  const dayNumber = dayNames.indexOf(dayName);
  mm -= 1; // JS months start at 0
  return days.filter(d => {
    const date = new Date(yyyy, mm, d);
    return mm === date.getMonth() && dayNumber === date.getDay()
  });
};

console.log(
  getDates(2020, 9, "Wednesday")
)
console.log(
  getDates(2020, 9, "Monday")
)

/* Without the need for a dayName array but needing the month name as input

**NOTE** this was more for my own entertainment - the date constructor may fail on some browsers that does not like `new Date("Monday, August 31")` such as Safari
*/

const fm = new Intl.DateTimeFormat('en-US',{dateStyle:"full"}),
    days = [...Array(32).keys()].splice(1); // generate 1-31

const getDates = (yyyy, monthName, dayName) => {
    const mn = monthName.slice(0,3);
    return days.filter(d => {
      const [,dn,month,day] = fm.format(new Date(`${mn} ${d}, ${yyyy}`)).match(/(\w+?), (\w+?) (\d+?),/)
      return dayName===dn && monthName === month;
    });
};
console.log(
  getDates(2020, "September", "Wednesday")
)
console.log(
  getDates(2020, "August", "Monday")
);  

Upvotes: 1

Related Questions